通过antd的官方文档我们可以知道如何使用checkbox来完成多选和单选的切换。
https://ant.design/components/checkbox/
我的问题是,如果我的复选框数据来自后端服务,我应该如何维护我的数据?准确地说,当我将数据保存为类状态时,对 UI 的更改可能会受到官方文档等数据更改的影响。
现在我尝试在渲染Dom时遍历后端数据,如下示例代码:
import { Checkbox } from 'antd';
const CheckboxGroup = Checkbox.Group;
class App extends React.Component {
state = {
indeterminate: true,
checkAll: false,
};
render() {
return (
<div>
<div style={{ borderBottom: '1px solid #E9E9E9' }}>
<Checkbox
indeterminate={this.state.indeterminate}
onChange={this.onCheckAllChange}
checked={this.state.checkAll}
>
Check all
</Checkbox>
</div>
<br />
{
this.renderDomFunction(data)
}
</div>
);
}
// data is from back-end server
renderDomFunction = (data) => {
let plainOptions = []
let defaultCheckedList = []
let dom
data.map(item => {
plainOptions.push(
{
label: <div>this is Orange</div>,
value: 'Orange',
disabled: false
},
{
label: <div>this is Apple</div>,
value: 'Apple',
disabled: false
},
)
defaultCheckedList.push('Orange','Apple')
})
return (
dom = <li>
<CheckboxGroup
options={plainOptions}
value={defaultCheckedList}
onChange={this.onChange}
/>
</li>
)
}
onChange = () => {
// code...
// I can't change the state of the checkbox by changing the data now, because isn't maintained in the state of Class.
}
}
ReactDOM.render(<App />, mountNode);
我还尝试将 setstate() 函数放入 renderDomFunction 中,但这会导致无限循环。
谢谢!