首页 > 解决方案 > 如何在 React 中使用 useState 检查复选框的更改值

问题描述

我会将带有属性的复选框字段列表传递给我的组件,我想checked根据人的选择来更改属性的值,但我能做的最多是将数组中的检查值加倍。

如何在我的状态下更改此特定密钥?

这是我的代码:

export default function Combocheck({ data, title, id }) {
  const inputLabel = React.useRef(null);

  const [state, setState] = React.useState({
    checkbox: data.map((element) => {
      element.checked = false;
      return element;
    })
  });

  const changeState = name => event => {
    const newValue = !state.checkbox[name].checked;
    setState({ checkbox: [
        ...state.checkbox,
        state.checkbox[name] = {
          ...state.checkbox[name],
          checked: newValue
        }
      ]
    });
  }

  console.log(state);

  return (
    <div> 
      <Typography color='textSecondary'>{title}</Typography>
      <Divider />
      <FormGroup>
        {state.checkbox.map(({code, description, checked}, i) => {
          return <FormControlLabel control={
            <Checkbox
              key={code}
              checked={checked}
              onChange={changeState(i)}
              value={code}
              color="primary"
            />
          }
          key={code}
          label={description}
          />
        })}
      </FormGroup>
    </div>
  );
}

可以在这里查看或编辑:https ://stackblitz.com/edit/react-irhqw9?file=Hello.js

标签: javascriptreactjs

解决方案


每次更新状态时,您都会添加一个复选框项目!相反,请考虑映射您的元素并仅更改适用的元素:

const changeState = name => event => {
  setState({ 
    checkbox: state.checkbox.map((checkbox, i) => {
      return i !== name ? 
        checkbox : 
        { ...checkbox, checked: !checkbox.checked }
    }) 
  });
}

我也不喜欢使用元素索引作为名称。我很确定你会很好地使用代码(假设它是唯一的),然后这不需要是一个更高阶的函数:

const changeState = event => {
  setState({ 
    checkbox: state.checkbox.map((checkbox) => {
      return event.target.value !== checkbox.code ? 
        checkbox : 
        { ...checkbox, checked: !checkbox.checked }
    }) 
  });
}

然后在Checkbox道具中:

onChange={changeState}

推荐阅读