简体   繁体   English

使用 useState 更新 React 中多个复选框的 state

[英]Update state of multiple checkboxes in React with useState


I am quite new to react.js so please apologise if I am not getting everything on the first try.我对 react.js 很陌生,所以如果我在第一次尝试时没有得到所有东西,请道歉。

My problem is that I do not understand how to update the state of a checkbox by using hooks.我的问题是我不明白如何使用钩子更新复选框的 state。

This is the code I am using to generate my checkboxes (from react-bootstrap):这是我用来生成复选框的代码(来自 react-bootstrap):

Checkbox Component :复选框组件

        <Form.Group controlId="briefing">
          {['Component1', 'Component2', 'Component3', 'Component4'].map((component)=>(
            <Form.Check
              custom
              inline
              label={component}
              name={component}
              type="checkbox"
              id={`module-component-${component}`}
              onChange={(e)=>handleComponentChange(e)}
            />
          ))}
        </Form.Group>

handleComponentChange() :处理组件更改()

const [inputs, setInputs] = useState({});

const handleComponentChange = (event) => {
  event.persist()

  setInputs(inputs=>({
    ...inputs,
    components:{
      ...inputs.components,
      name:event.target.name
    }
  }))  
}

the ...inputs comming from other input fields I have in this form.来自我在此表单中的其他输入字段的...inputs

This is not working how I would like to.这不是我想要的。 The state is getting updated but overwritten by the last checked item: state 正在更新,但被最后一个检查项目覆盖:

    {
      "components":{
        "name":"Component1"
      },
        "customfield_10313":"Input 1",
        "customfield_10411":"Input 2",
        "customfield_10405":"Input 3",
        "customfield_10385":"input 4"
    }

What I would like to see as the result is something like this:我希望看到的结果是这样的:

{
  "components":[
  {
     "name":"Component1"
  },
  {
     "name":"Component2"
  },
  {
     "name":"Component3"
  },
  {
     "name":"Component4"
  }
  ]
}

I need this structure for an API call.我需要这个结构来调用 API。

I know that you need to check if the checkbox is already checked and then remove the item if so.我知道您需要检查复选框是否已被选中,如果是,则删除该项目。 That's my next problem.那是我的下一个问题。

Thank you for any input!感谢您的任何意见!

Since you want you components state to contain an array, you need to update it like one.由于您希望组件 state 包含一个数组,因此您需要像更新它一样更新它。 Also you would need to make sure to remove items from list when you uncheck a checkbox ie when item was already in the array此外,当您取消选中复选框时,即当项目已经在数组中时,您需要确保从列表中删除项目

const handleComponentChange = (event) => {
  event.persist()

  setInputs(inputs=>{
   // find it component is already there. If yes remove it
   const index = inputs.components.findIndex(item => item.name === event.target.name);
   if(index > -1) {
       return {
          ...inputs,
          components: [
            ...inputs.components.slice(0, index),
            ...inputs.components.slice(index + 1),
          ]
       }
    } else {
       // push item into array
       return {
          ...inputs,
          components: inputs.components.concat({name: event.target.name}),
       }
    }
  }) 
}

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

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