简体   繁体   English

从复选框组中获取值并从数组中添加/删除它们

[英]Getting values from checkbox group and adding/removing them from array

I am creating a form where I have a group of checkboxes.我正在创建一个表单,其中有一组复选框。

When click on checkbox, I would get the value of that specific checkbox and add to an Array (I am using the useState hook) and if I uncheck it will remove that element from the array.单击复选框时,我将获取该特定复选框的值并添加到数组(我正在使用 useState 挂钩),如果我取消选中它将从数组中删除该元素。

That's my code so far:到目前为止,这是我的代码:

const ContactUs = () => {
  const [cities, setCities] = useState([])

  useEffect(() => {
    console.log(cities)
  })

  const handleCheck = (e) => {
    if (e.target.checked) {
      setCities([...cities, e.target.value])
    } else {
      removeCities()
    }
  }

  const removeCities = () => {
    setCities(() => cities.splice(DT.length - 1, 1))
  }

  return (
    <Content>
      <form>
        <SectionTitle>Day Tours</SectionTitle>

        <Checkbox
          type="checkbox"
          id="1"
          label="Dublin"
          value="dublin"
          name="dublin"
          onChange={handleCheck}
        />
        <Checkbox
          type="checkbox"
          id="2"
          label="New York"
          value="New York"
          name="new-york"
          onChange={handleCheck}
        />
        <Checkbox
          type="checkbox"
          id="3"
          label="Torino"
          value="Torino"
          name="torino"
          onChange={handleCheck}
        />
      </form>
    </Content>
  )
}

I can add it to the array but I can't seem to remove it (or remove the right one).我可以将它添加到数组中,但似乎无法删除它(或删除正确的)。

I tried splice and slice methods but as I don't fully grasp their concept.我尝试了拼接和切片方法,但因为我没有完全掌握它们的概念。

I don't know what is DT as you haven't shared your whole code, but I think you can approach this in another still functional, declarative way:我不知道什么是DT ,因为您还没有共享整个代码,但我认为您可以通过另一种功能性、声明性的方式来解决这个问题:

Filter out the array so it returns everything that is checked and filters (removes) the unchecked ones:过滤掉数组,使其返回所有已检查的内容并过滤(删除)未检查的内容:

in your else block:在你的 else 块中:

setCities(cities.filter(city => city.== e.target.value))

Filter will always return a new array with the values that match the filter criteria, in this case it would return everything except the e.target.value , which is what we want as based on your logic, the else block will execute when it's unchecked. Filter 将始终返回一个新数组,其值与过滤条件匹配,在这种情况下,它将返回除e.target.value之外的所有内容,这是我们根据您的逻辑想要的,else 块将在未选中时执行.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM