How to checked multiple checkbox in react.js?

拈花ヽ惹草 提交于 2020-04-27 10:48:03

问题


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 checkbox . One is Select All Checkbox . it actually works when user click on the Select All or User select on all individual checkbox . Other is individual checkbox , user can Select on individually . when user submit on Button , then it's give me this data format ["manage_books","manage_journals","manage_deals"]

here is my trying code :

 let defaultCheckedList = ["manage_deals"];


state = {
    groupKey: [{
            id: 1,
            key: "manage_books",
            label: "books"
        },
        {
            id: 2,
            key: "manage_journals",
            label: "journals"
        },
        {
            id: 3,
            key: "manage_deals",
            label: "deals"
        }
    ],
    checkedList: defaultCheckedList,
    output: [],
    indeterminate: true,
    checkAll: false
};
onCheckAllChange = e => {
    this.setState({
        checkedList: e.target.checked ?
            this.state.groupKey.map(item => item.key) :
            [],
        indeterminate: false,
        checkAll: e.target.checked
    });
};

onChange = (e, value) => {
    this.setState({
        checked: e.target.checked,
        output: this.state.output.concat(value)
    });
};
onSubmit = () => {
    console.log(this.state.output)
}

render(UI)

    <
    div >
    <
    div className = "site-checkbox-all-wrapper" >
    Select All <
    Checkbox
indeterminate = {
    this.state.indeterminate
}
onChange = {
    this.onCheckAllChange
}
checked = {
    this.state.checkAll
}
/> <
/div>

I am looping checkbox by groupKey.I am passing key using onChange method. {
        this.state.groupKey.map(item => ( <
            div className = "userpermission-content"
            key = {
                item.id
            } > {
                item.label
            } <
            Checkbox onChange = {
                (e, value) => this.onChange(e, item.key)
            }
            value = {
                item.key
            }
            />{" "} <
            /div>
        ))
    } <
    button onClick = {
        this.onSubmit
    } > submit < /button> <
    /div>
);
}
}

In this code, you can see that two individual checkbox is initial select, I need to get completely like this: https://codesandbox.io/s/4k6qi

this is my codesanbox: https://codesandbox.io/s/check-all-ant-design-demo-vhidd?file=/index.js


回答1:


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


来源:https://stackoverflow.com/questions/61089573/how-to-checked-multiple-checkbox-in-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!