How to use checkbox to achieve multiple selection and single selection?

512 Views Asked by At

Through the official documentation of antd we can know how to use the checkbox to complete the switch between multiple selection and single selection.

https://ant.design/components/checkbox/

My question is, if my checkbox data comes from a backend service, how should I maintain my data? It's accurate to say when I save the data in state of class so that the changes to the UI can be affected by changes in the data like the official documentation.

Now I try to traverse the back-end data when rendering the Dom, the following example code:

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);

I also tried to put the setstate() function into the renderDomFunction but this would cause an infinite loop.

Thank you!

0

There are 0 best solutions below