How to checked multiple checkbox in react.js?

后端 未结 1 1796
刺人心
刺人心 2020-12-12 07:49

I am using react antd . I have got array of objects that\'s groupKey .I am mapping checkbox by using Groupkey and also I have got two different types of che

相关标签:
1条回答
  • 2020-12-12 08:36

    Here is what I have come up with

    https://codesandbox.io/s/check-all-ant-design-demo-6cm2v?file=/index.js

    import React from "react";
    import ReactDOM from "react-dom";
    import "antd/dist/antd.css";
    import "./index.css";
    import { Checkbox } from "antd";
    
    const CheckboxGroup = Checkbox.Group;
    
    class App extends React.Component {
      state = {
        groupKey: [
          { id: 1, key: "manage_books", label: "books" },
          { id: 2, key: "manage_journals", label: "journals" },
          { id: 3, key: "manage_deals", label: "deals" }
        ],
        checked: {},
        output: [],
        indeterminate: true,
        checkAll: false
      };
      onCheckAllChange = e => {
        const { groupKey } = this.state;
        const checked = groupKey.reduce((prev, curr) => {
          return { ...prev, [curr.key]: e.target.checked };
        }, {});
        this.setState({ checked, checkAll: e.target.checked });
      };
      checkAll = () => {};
      onChange = (e, value) => {
        // this.setState({
        //   checked: e.target.checked,
        //   output: this.state.output.concat(value)
        // });
        this.setState(
          state => ({
            checked: { ...state.checked, [value]: e.target.checked }
          }),
          () => {
            const { checked, groupKey } = this.state;
            const values = Object.values(checked);
            if (values.length === groupKey.length && values.every(v => v)) {
              this.setState({ checkAll: true });
            } else {
              this.setState({ checkAll: false });
            }
          }
        );
      };
      render() {
        console.log(this.state.output);
        const { checked, checkAll } = this.state;
        return (
          <div>
            <div className="site-checkbox-all-wrapper">
              Select All
              <Checkbox
                // indeterminate={this.state.indeterminate}
                onChange={this.onCheckAllChange}
                checked={checkAll}
              />
            </div>
            {this.state.groupKey.map(item => (
              <div className="userpermission-content" key={item.id}>
                {item.label}
                <Checkbox
                  onChange={e => this.onChange(e, item.key)}
                  value={item.key}
                  checked={checked[item.key]}
                />{" "}
              </div>
            ))}
          </div>
        );
      }
    }
    
    ReactDOM.render(<App />, document.getElementById("container"));

    0 讨论(0)
提交回复
热议问题