【问题标题】:Update state of multiple checkboxes in React with useState使用 useState 更新 React 中多个复选框的状态
【发布时间】:2020-05-22 10:56:53
【问题描述】:


我对 react.js 很陌生,所以如果我在第一次尝试时没有得到所有东西,请道歉。

我的问题是我不明白如何使用钩子更新复选框的状态。

这是我用来生成复选框的代码(来自 react-bootstrap):

复选框组件

        <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
    }
  }))  
}

...inputs 来自我在此表单中的其他输入字段。

这不是我想要的。状态正在更新,但被最后检查的项目覆盖:

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

我希望看到的结果是这样的:

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

我需要这个结构来进行 API 调用。

我知道您需要检查复选框是否已被选中,如果是,则删除该项目。 这是我的下一个问题。

感谢您的任何意见!

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    由于您希望组件状态包含一个数组,因此您需要像更新它一样更新它。此外,您还需要确保在取消选中复选框时从列表中删除项目,即当项目已经在数组中时

    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}),
           }
        }
      }) 
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-25
      • 2020-05-12
      • 2019-10-17
      • 1970-01-01
      • 2021-01-06
      • 2021-03-12
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      相关资源
      最近更新 更多