【发布时间】:2016-12-22 11:44:56
【问题描述】:
我有一个带有复选框的项目列表。当单击任何项目的复选框时,会显示某些操作(添加、删除、移动等)以将这些操作应用于该选定项目。我也可以实现检查所有按钮来检查所有项目并取消选中它。但是如果我检查一个项目,所有项目都会被选中,并且在取消选中时都是一样的。
这是我的代码
var Device = React.createClass({
getInitialState() {
return {
checked: []
}
},
handleChange(e, key) {
let checked = this.state.checked.slice();
if (e.target.checked) {
checked.push(key);
console.log('checked before removing', checked);
}
else {
checked.splice(checked.indexOf(key), 1);
console.log('checked after removing', checked);
// checked.filter((x, i) => checked.splice(checked.indexOf(key), 1));
}
this.setState({ checked: checked });
},
checkAll() {
this.setState({
checked: this.props.devices.entrySeq().map(([key, value]) => key)
}).toArray();
},
uncheckAll() {
this.setState({ checked: [] });
},
render() {
const { checked } = this.state;
let devices = this.props.devices.entrySeq().map(([key, value]) => {
let url = '/device/'+value.get('id');
let name = value.get('name');
return (
<RowGroup key={key}>
<Row>
<Cell>
<input
type="checkbox"
name={name}
checked={checked.indexOf(key) !== -1}
onChange={(e) => this.handleChange(e, key)}
/>
</Cell>
<RouterLink to={url}>
<Cell>
{name}
</Cell>
</RouterLink>
</Row>
</RowGroup>
);
}).toArray();
return (
<div>
{ checked.length !== 0 ? <DeviceActions uncheckAll={() => this.uncheckAll()} /> :
<GlobalDeviceActions
checkAll={() => this.checkAll()}
uncheckAll={() => this.uncheckAll()}
/>
}
<Table>
{devices}
</Table>
</div>
);
},
});
const mapDispatchToProps = function(dispatch) {
return {};
}
const mapStateToProps = createStructuredSelector({
devices: selectDevices()
});
export default connect(mapStateToProps, mapDispatchToProps)(Device);
const DeviceActions = (props) => (
<div>
<Actions>
<Uncheck onClick={props.uncheckAll} />
<Add />
<Move />
</Actions>
</div>
);
export const GlobalDeviceActions = (props) => (
<div>
<Actions>
<Check onClick={props.checkAll} />
<Uncheck onClick={props.uncheckAll} />
</Actions>
</div>
);
export default DeviceActions;
使用来自@Jonny Buchanan 的更新代码,一切正常,但是当一次检查所有项目时,我无法取消选中单个项目。我一次只能取消选中整个项目。
更新
它现在正在工作。在 checkAll 函数中,我必须将集合转换为数组。我猜,它是因为集合是生成器,它不会立即执行,所以我必须将它变异为一个数组。
【问题讨论】:
标签: javascript reactjs redux