背景:点击全部按钮,让展示的复选框全部选中,复选框使用的是Checkbox标签
代码:
{this.state.jgmcData.map((item, i) => { return (<Checkbox onChange={this.onChange.bind(this, item)} value={item.id} checked={this.state.checkedIds.includes(item.id)}> //此处是重点 </Checkbox>) })}
按钮:<Button primary className={suse.cancelConcern} onClick={() => this.onCheckAllChange()} > 选择全部</Button>
js代码:
选择全部事件: onCheckAllChange = () => { let { pageFindList } = this.state; let checkedIdsFromList = pageFindList.map((item, idx) => { return item.id; }); this.setState({ checkedIds: checkedIdsFromList, }); };
单个复选框改变事件(增删改):onChange = (item) => { let { checkedIds } = this.state; if (checkedIds.includes(item.id)) { checkedIds.forEach((itemInner, idx) => { if (itemInner == item.id) { checkedIds.splice(idx, 1); } }); } else { checkedIds.push(item.id); } this.setState({checkedIds: checkedIds, }); };
总结:在复选框上加入value属性,然后点击全选的额时候将所有复选框的id放到一个数组变量中,然后在标签上使用“checked={this.state.checkedIds.includes(item.id)}>”判断赋值的变量中是否包含改复选框上得value,包含了则checked成立