React获取复选框中的已选值

huangapple go评论65阅读模式
英文:

React retrieve checked value in checkbox

问题

我正在尝试检索复选框的选中值并将它们保存到数组中。
我尝试了:

arr.push(setNewItem(checked))
arr.push(e.target.value.checked)
arr.push(items.checked)

但这些返回类型错误或未定义值。

const [checkedItems, setCheckedItems] = useState([]);
const handleChange = (e) => {
    if (e.target.checked) {
      var arr = [...checkedItems];
      //arr.push(setNewItem(e.target.value.checked));
      setCheckedItems(arr);
      console.log(arr);
    } else {
      checkedItems = "";
    }
    setIsChecked((current) => !current);
};
return (
    <div className="App">
      <StyleForm>
        <StyleInput
          type="text"
          placeholder="Add"
          value={newItem}
          onChange={(e) => setNewItem(e.target.value)}
          onKeyPress={handleOnKeyPress}
        />
        <ButtonAddStyle onClick={() => addItem()}>add</ButtonAddStyle>

        <StyleUl>
          {items.map((item) => {
            return (
              <StyleLi key={item.id}>
                <StyleCheckBox
                  type="checkbox"
                  value={isChecked}
                  onChange={handleChange}
                />
                {item.value}
                {""}
                <ButtonDelStyle onClick={() => deleteItem(item.id)}>
                  X
                </ButtonDelStyle>
              </StyleLi>
            );
          })}
        </StyleUl>
      </StyleForm>
    </div>
  );

请注意,你的代码中有一些问题,如setNewItem(checked)e.target.value.checkeditems.checked可能不是你要用来获取复选框选中状态的正确方式。你需要检查复选框的状态,并相应地更新checkedItems数组。希望这有所帮助。

英文:

I am trying to retrieve the checked values of the checkboxes and save them into array.
I tried :

arr.push(setNewItem(checked))
arr.push(e.target.value.checked)
arr.push(items.checked)

But these return type error or undefined values.

const [checkedItems, setCheckedItems] = useState([]);
const handleChange = (e) =&gt; {
    if (e.target.checked) {
      var arr = [...checkedItems];
      //arr.push(setNewItem(e.target.value.checked));
      setCheckedItems(arr);
      console.log(arr);
    } else {
      checkedItems = &quot;&quot;;
    }
    setIsChecked((current) =&gt; !current);
  };
return (
    &lt;div className=&quot;App&quot;&gt;
      &lt;StyleForm&gt;
        &lt;StyleInput
          type=&quot;text&quot;
          placeholder=&quot;Add&quot;
          value={newItem}
          onChange={(e) =&gt; setNewItem(e.target.value)}
          onKeyPress={handleOnKeyPress}
        /&gt;
        &lt;ButtonAddStyle onClick={() =&gt; addItem()}&gt;add&lt;/ButtonAddStyle&gt;

        &lt;StyleUl&gt;
          {items.map((item) =&gt; {
            return (
              &lt;StyleLi key={item.id}&gt;
                &lt;StyleCheckBox
                  type=&quot;checkbox&quot;
                  value={isChecked}
                  onChange={handleChange}
                /&gt;
                {item.value}
                {&quot;&quot;}
                &lt;ButtonDelStyle onClick={() =&gt; deleteItem(item.id)}&gt;
                  X
                &lt;/ButtonDelStyle&gt;
              &lt;/StyleLi&gt;
            );
          })}
        &lt;/StyleUl&gt;
      &lt;/StyleForm&gt;
    &lt;/div&gt;
  );

答案1

得分: 3

arr.push(e.target.checked);
这是正确的方法,可以摆脱:

else {
checkedItems = "";
}
不能使用这种方式更新状态,当尝试取消选中输入时会出现错误:
> Uncaught TypeError: Assignment to constant variable

现在让我们看看您试图做什么,您每次检查输入时都会存储`e.target.checked`,因此`checkedItems`将看起来像这样:

[true, true, true, true, true, true, true, true]
你为什么需要这个?更好的方法是存储已选项目的ID:

const handleChange = (isChecked, id) => {
  var arr = [...checkedItems];
  if (isChecked) {
    arr.push(id);
    setCheckedItems(arr);
  } else {
    setCheckedItems(checkedItems.filter((storedId) => storedId !== id)); // 如果对应的输入取消选中,则从checkedItems中删除ID
};

并且从jsx:
<StyleCheckBox
  type="checkbox"
  value={item.id}
  onChange={(e) => {
    handleChange(e.target.checked, item.id);
  }}
/>;

现在看这个:
<StyleCheckBox
  value={isChecked} // 这一行
>;

您正在通过`items`进行映射,创建多个复选框,但它们都共享相同的值。复选框类型输入的值属性不是您想象的那样,可以在这里了解更多信息(https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox#value)。因此,您可以使用`value={item.id}`来为每个输入提供唯一的值,然后摆脱`isChecked` useState 钩子,您真的不需要它。
英文:
arr.push(e.target.checked);

Is the way to go and get rif of :

else {
checkedItems = &quot;&quot;;
}

you cannot update a state this way, you will get an error when you try to unchek an input:
>Uncaught TypeError : Assignment to constant variable

Now let's see what you are trying to do you are storing e.target.checked each time an input is cheked so checkedItems will look something like this :

[true, true, true, true, true, true, true, true]

why do you need this ? better is to store the ids of checked items :

const handleChange = (isChecked, id) =&gt; {
  var arr = [...checkedItems];
  if (isChecked) {
    arr.push(id);
    setCheckedItems(arr);
  } else {
    setCheckedItems(checkedItems.filter((storedId) =&gt; storedId !== id)); // delete the id from checkedItems if the corresponding input is unckecked
  }
};

and from jsx :

&lt;StyleCheckBox
  type=&quot;checkbox&quot;
  value={item.id}
  onChange={(e) =&gt; {
    handleChange(e.target.checked, item.id);
  }}
/&gt;;

Now look at this :

&lt;StyleCheckBox
  value={isChecked} // this line
&gt;

you are mapping through items creating multiple checkBoxes but all of them share the same value. and the value attribute of an input of type checkbox is not what you think it is, learn more here. so you can use value={item.id} to have an unique value for each input and get rid of isChecked useState hook you really don't need it

答案2

得分: 0

这可能解决你的问题。

const [checkedItems, setCheckedItems] = useState([]);
const handleChange = (e) => {
  setCheckedItems(prev => [...prev, e.target.checked]);
  setIsChecked((current) => !current);
};
英文:

this could solve your problem.

const [checkedItems, setCheckedItems] = useState([]);
const handleChange = (e) =&gt; {
  setCheckedItems( prev =&gt; [...prev, e.target.checked]);
  setIsChecked((current) =&gt; !current);
};

huangapple
  • 本文由 发表于 2023年2月8日 11:25:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75381114.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定