【问题标题】:How to work with multiple checkboxes in react and collect the checked checkboxes如何在反应中使用多个复选框并收集选中的复选框
【发布时间】:2021-11-10 16:12:19
【问题描述】:

我目前正在开发一个可以选择多个复选框的过滤器组件。

现在我想切换复选框的状态(目前可行且有效)并将选中的复选框存储在一个数组中。

如果一个复选框未被选中,它当然应该从数组中删除。我试过 useState 钩子,但没有成功 --> 复选框被添加了多次,未选中的没有被删除..

这是当前状态:

  // Here I'm creating an array with a fixed size (based on the received data)
  const [checkboxState, setCheckboxState] = useState(new Array(receivedData.length).fill(false));
  // With this useState I wan't to collect the checked checkboxes
  const [checkedCheckboxes, setCheckedCheckboxes] = useState([]);
    
  // This is my handler method that gets triggered when a checkbox get's checked/unchecked
  // ..and toggles the state of the checkbox
  const handleCheckboxState = (position: number) => {
    const updatedCheckedState = checkboxState.map((item, index) => (index === position ? !item : item));
    setCheckboxState(updatedCheckedState);
    collectCheckedCheckboxes();
  };

  // With this method I wan't to push the checked checkboxes into the array
  // ..and remove the unchecked ones
  const collectCheckedCheckboxes = () => {
    checkboxState.map((item, index) => {
      if (item === true) {
        return checkedCheckboxes.push(receivedData[index]);
      } else {
        return checkedCheckboxes.slice(index, 1);
      }
    });
  };

复选框呈现如下:

  <div className="checkboxes">
    {receivedData?.map((data, index) => (
      <CheckBox
        value={data.value}
        checked={checkboxState[index]}
        onChange={() => handleCheckboxState(index)}
      />
    ))}
  </div>

我做错了什么?

【问题讨论】:

    标签: javascript reactjs typescript react-hooks react-state-management


    【解决方案1】:

    您的CheckBox-组件不包含key 属性。这有助于 React 识别哪些项目已更改、添加或删除。

    来源:https://reactjs.org/docs/lists-and-keys.html

    我也不明白为什么你有两个状态,checkboxStatecheckedCheckboxes。还有其他原因吗?我认为使用包含选中复选框的索引(或值)的单个状态会更容易。

    [cmets 后更新]

    以下代码是 OP 所需的解决方案,以使所选对象值处于 React 状态。

    const { useState } = React;
    
    const Checkboxes = () => {
      // With this useState I wan't to collect the checked checkboxes
      const [checkedCheckboxes, setCheckedCheckboxes] = useState([]);
    
      // This is my handler method that gets triggered when a checkbox get's checked/unchecked
      // ..and toggles the state of the checkbox
      const handleCheckboxChange = (data) => {
        const isChecked = checkedCheckboxes.some(checkedCheckbox => checkedCheckbox.value === data.value)
        if (isChecked) {
          setCheckedCheckboxes(
            checkedCheckboxes.filter(
              (checkedCheckbox) => checkedCheckbox.value !== data.value
            )
          );
        } else {
          setCheckedCheckboxes(checkedCheckboxes.concat(data));
        }
      };
    
      const receivedData = [{ value: "A" }, { value: "B" }, { value: "C" }];
    
      return (
        <>
          <div className="checkboxes">
            <h1>Checkboxes:</h1>
            {receivedData?.map((data, index) => (
              <input
                key={`cb-${index}`}
                value={data.value}
                type="checkbox"
                checked={checkedCheckboxes.some(checkedCheckbox => checkedCheckbox.value === data.value)}
                onChange={() => handleCheckboxChange(data)}
              />
            ))}
          </div>
          <div>
            <h1>State:</h1>
            <pre>{JSON.stringify(checkedCheckboxes, null, 2)}</pre>
          </div>
        </>
      );
    };
    
    ReactDOM.render(<Checkboxes />, document.getElementById("app"));
    

    【讨论】:

    • 我刚刚发布了我的代码的简单版本。我还插入了密钥 :) 感谢您的方法,但是您如何跟踪复选框的状态? ..and concat 从数组中移除元素?
    • .concat 将元素添加到数组中,.filter 删除元素。您只需要跟踪选中的复选框。由于receivedData,可用的复选框是已知的,因此选中的复选框数组应该足够了吗?
    • 哦,对了,我错了。我会试一试并给你反馈。谢谢:)
    • 现在可以了!非常感谢 :) - 如果需要,您可以在上面更新您的答案,以便我将其标记为解决方案。
    • 很高兴听到 :) 不客气。我已经使用 codepen 的代码更新了解决方案。祝你的项目好运!
    猜你喜欢
    • 2022-11-09
    • 1970-01-01
    • 2022-10-13
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多