问题描述
我正在使用react antd.这段代码可以正常工作,但是我想替换<CheckboxGroup/>
.现在,我只是在<CheckboxGroup/>
内部传递了plainOptions数组而不进行循环,但是现在我想通过使用plainOptions数组来循环单个<Checkbox>
.
I am using react antd. this code is worked perfectly , but I want to replace <CheckboxGroup/>
. Now , I am just pass plainOptions array inside <CheckboxGroup/>
without looping, but right now I want to do loop single <Checkbox>
by using plainOptions array.
For example : plainOptions.map(item=><Checkbox value={item} onChange
{this.onChange}/>) ) // My code would be like this
const plainOptions = ['Apple', 'Pear', 'Orange'];
const defaultCheckedList = ['Apple', 'Orange'];
class App extends React.Component {
state = {
checkedList: defaultCheckedList,
indeterminate: true,
checkAll: false,
};
onChange = checkedList => {
this.setState({
checkedList,
indeterminate: !!checkedList.length && checkedList.length < plainOptions.length,
checkAll: checkedList.length === plainOptions.length,
});
};
onCheckAllChange = e => {
this.setState({
checkedList: e.target.checked ? plainOptions : [],
indeterminate: false,
checkAll: e.target.checked,
});
};
<div className="site-checkbox-all-wrapper">
<Checkbox
indeterminate={this.state.indeterminate}
onChange={this.onCheckAllChange}
checked={this.state.checkAll}
>
Check all
</Checkbox>
</div>
<br />
<CheckboxGroup
options={plainOptions}
value={this.state.checkedList}
onChange={this.onChange}
/>
我想使用 <Checkbox/>
而不是CheckboxGroup.我的代码就是这样
I want to use <Checkbox/>
instead of CheckboxGroup. My code would be like this
For example : plainOptions.map(item=><Checkbox value={item} onChange
{this.onChange}/>)
如何完成?
这是我的代码sanbox: https://codesandbox.io/s/4k6qi ?file =/index.js
Here is my codesanbox: https://codesandbox.io/s/4k6qi?file=/index.js
推荐答案
不需要多个状态,只需保留一个单一来源(checkedList
)就可以了.
There is no need for multiple states, keep one single source (checkedList
) would be fine.
onCheckItem = value => e => {
const { checkedList } = this.state;
this.setState({
checkedList: checkedList.includes(value)
? checkedList.filter(x => x !== value)
: [...checkedList, value]
});
};
render() {
const { checkedList } = this.state;
return (
<div>
<div className="site-checkbox-all-wrapper">
<Checkbox
indeterminate={
checkedList.length < plainOptions.length && checkedList.length > 0
}
onChange={this.onCheckAllChange}
checked={checkedList.length === plainOptions.length}
>
Check all
</Checkbox>
</div>
<br />
{plainOptions.map((item, idx) => (
<Checkbox
key={item + idx}
onChange={this.onCheckItem(item)}
checked={checkedList.includes(item)}
>
{item}
</Checkbox>
))}
</div>
);
}
这篇关于如何选择多个复选框reactjs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!