javascript - 如何在 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
解决方案
每次更新状态时,您都会添加一个复选框项目!相反,请考虑映射您的元素并仅更改适用的元素:
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}
推荐阅读
- reactjs - 材质 UI - 文件上传 -
- android - 使用颤振在后台扫描和收听来自蓝牙设备的事件
- node.js - 获取公共 graphql 订阅的所有订阅者的列表
- ruby - 在 ruby c 扩展中记录方法
- google-api - 撤销谷歌服务账户访问令牌
- javascript - React Redux - TypeError:无法读取未定义的属性“道具”
- mysql - Magento 2 - 从数据库更改图像角色
- django - 具有多个值的 Django 模型字段
- c++ - fstream 无法打开文件
- django - VSCode 用换行符打破 Django 模板标签