我使用Set data structure切换复选框。目前,该检查正在工作,但取消选中不工作。检查时,我发送所选项目的键/id,取消检查时,我试图删除该键,但它转换了整个
checked
状态为布尔值。相反,它应该给我checked state的值
{'key1', 'key2'}
不包括“key3”,因为key3的项未选中。不可变.js的集合,用于工作,但不在本机javascript中。
这就是我所做的
class DeviceHome extends React.Component<propsCheck> {
constructor() {
super();
this.state = { checked: new Set(), group: '' };
}
componentWillReceiveProps(nextProps) {
try {
if (!nextProps.activeGroup.equals(this.props.activeGroup)) {
this.setState({ checked: new Set() });
}
} catch (e) {}
}
toggle(key) {
const { checked } = this.state;
this.setState({
checked: checked.has(key) ? checked.delete(key) : checked.add(key),
});
}
toggleAll() {
const { checked } = this.state;
this.setState({
checked: checked.size === 0 ? checked.values(this.props.devices) : checked.clear(),
});
}
render() {
const { checked } = this.state;
console.log('checked', checked, typeof checked);
const indeterminate = Boolean(checked.size) && checked.size < Object.keys(this.props.devices).length;
const devices = Object.entries(this.props.devices).map(([key, value]) => {
const { name, connection_timeout: connectionTimeout } = value;
return (
<Table.Row key={key} active={checked.has(key) || false}>
<Table.Cell>
<Checkbox checked={checked.has(key)} onChange={() => this.toggle(key)} />
</Table.Cell>
</Table.Row>
)
});
return (
<Wrapper>
<Table unstackable structured>
<Table.Row>
<Table.HeaderCell>
<Checkbox
onChange={() => this.toggleAll()}
indeterminate={indeterminate}
checked={
Boolean(checked.size) &&
checked.size === Object.keys(this.props.devices).length
}
/>
</Table.HeaderCell>
</Table.Row>
<Table.Body>{devices}</Table.Body>
</Table>
</Wrapper>
)
}
}
只有清除/取消选中部分不起作用,因为它将数据结构更改为布尔值。