如下图所示更改您的状态,以在状态对象中选中复选框:
由此:
state = {
isAllSelected: false,
checked: {}
};
希望您的数据如下所示:
const options = [
{
name: "city",
value: "bangalore"
},
{
name: "city",
value: "chennai"
},
{
name: "city",
value: "delhi"
}
];
和
this.state = {
isAllSelected: false,
checked: options.reduce((r, a) => {
r[a.value] = false;
return r;
}, {}),
checkList: options
};
{bangalore: false, chennai: false, delhi: false}
onCheck(checkName, isChecked) {
let isAllChecked = (checkName === 'all' && isChecked);
let isAllUnChecked = (checkName === 'all' && !isChecked);
const checked = isChecked;
const newChecked = {...this.state.checked};
if(checkName === 'all' && isChecked) {
Object.keys(newChecked).forEach(v => newChecked[v] = true)
} else if(checkName === 'all' && !isChecked) {
checkName === 'all' && Object.keys(newChecked).forEach(v => newChecked[v] = false);
} else {
newChecked = { ...newChecked, [checkName]: checked };
}
let isAllCheckedNew = Object.keys(newChecked).every(function(k){ return newChecked[k] === true });
this.setState({
checked: newChecked,
isAllSelected: isAllCheckedNew || isAllChecked
});
完整的代码演示可用
here