【发布时间】:2020-12-01 22:57:39
【问题描述】:
我正在使用 mui 复选框组件,这就是我的显示方式:
<FormControl component="fieldset">
<FormGroup aria-label="position" column>
{sortedData.map((obj) => {
return (
<FormControlLabel
value="type"
control={<Checkbox color="primary"/>}
label={obj}
name={obj}
onChange={handleTypeCheckboxChange}
labelPlacement="end"
/>
);
})}
</FormGroup>
</FormControl>
现在在这个函数 handleTypeCheckboxChange 上,我想在用户选中或取消选中时添加或删除复选框的值。
这是我尝试做的,但它不起作用。它给了我 NaN:
const [typeValue, setTypeValue] = useState([]) // the state array where I wanna store the checkbox checked values
const handleTypeCheckboxChange = (event) => {
let typeValuesArray = []
let index
if (event.target.checked) {
setTypeCheckboxCount(prevState => prevState + 1)
typeValuesArray.push(+(event.target.name))
} else {
setTypeCheckboxCount(prevState => prevState - 1)
index = typeValuesArray.indexOf(+(event.target.name))
typeValuesArray.splice(index, 1)
}
setTypeValue(typeValuesArray)
}
我该如何解决这个问题?
【问题讨论】:
-
你应该在codesandbox上重现这个,这样其他人会更容易赶上