reactjs 如何处理通过map方法创建的多个复选框

tsm1rwdh  于 2023-04-29  发布在  React
关注(0)|答案(2)|浏览(88)

我在map(loop)中创建了多个复选框。我无法添加两个功能:
1.当用户单击任何复选框时,它应该显示复选框已选中
1.默认情况下,eventGoing变量中存在的所有event_id都应该被选中。

{
  products.map((post) => (
    <div>
      // eventGoing going contains the list of event ids which I extracted from DB
      if(eventGoing.indexOf(event_id) > -1)
      {
        // need to check the checkbox if event_id is within eventGoing variable
      }
      <input
        checked={checked}
        name="goingChk"
        value={"checkbox-" + post.event_id}
        type="checkbox"
        id={"checkbox-" + post.event_id}
        onClick={(e) => handleGoing(e, post.event_id)}
      />
      <br />
    </div>
  ));
}

忽略编码错误,因为我从2个不同的功能组件中提取代码。
请帮助我如何获得上述两个功能。

k10s72fa

k10s72fa1#

完整代码:

const fetchDataEmpty = (setProducts) => {
    axios
    .get('/get_data.php')
    .then((res) => {
        setProducts(res.data);
    })
    .catch((err) => {
        console.log("Err:",err);
    });
};

const  ParentTile = (props) => {
    const [products, setProducts] = useState([]);
    
    
    useEffect(()=>{
          fetchData(setProducts)
        },[type]) // []
    
    
    return (
        <div> 
            {products.map(post=><div> 
                <EventTile record={post}  />
            </div>);
        </div>);
    }

}


//EventTile.js

const EventTile = (record) => {
    return <>
        Record.eventName
        <input  name="goingChk" value={"checkbox-"+record.event_id} type="checkbox" id={"checkbox-"+record.event_id} onClick={e => handleGoing(e, record.event_id)} />
        <br>
    <>
}
ncgqoxb0

ncgqoxb02#

问题:

问题是您在单个布尔状态上保存值,这会导致问题(选中所有复选框)

解决方案

你可以试试

const products = []
  const [checkboxValues, setCheckboxValues] = React.useState(new Array(products.length).fill(false));

  const handleCheckboxChange = (index) => {
    const newValues = [...checkboxValues];
    newValues[index] = !newValues[index];
    setCheckboxValues(newValues);
  };

  return (
    <div>
      {checkboxValues.map((value, index) => (
        <input
          key={index}
          type="checkbox"
          checked={value}
          onChange={() => handleCheckboxChange(index)}
        />
      ))}
    </div>
  )

您可以在这段代码中使用replace products数组和您的products数组,应该可以正常工作。
不过如果你想在你的代码里面做,你可以这样做
当然这里的更新的例子
完整代码:

const fetchDataEmpty = (setProducts) => {
    axios
        .get('/get_data.php')
        .then((res) => {
            const data = res.data?.map((item) => {
                return { ...item, checkboxValue: false }
            })
            setProducts(res.data);
        })
        .catch((err) => {
            console.log("Err:", err);
        });
};

const ParentTile = (props) => {
    const [products, setProducts] = useState([]);

    useEffect(() => {
        fetchData(setProducts)
    }, [type]) // []

    const handleCheckboxChange = (index) => {
        const newValues = [...checkboxValues];
        newValues[index].checkboxValue = !newValues[index].checkboxValue;
        setCheckboxValues(newValues);
    };

    return (
        <div>
            {products?.map((item, index) => (
                <input
                    key={index}
                    type="checkbox"
                    checked={item.checkboxValue}
                    onChange={() => handleCheckboxChange(index)}
                />
            ))}
        </div>
    );
}

相关问题