如何限制React JS中选中的复选框的数量?

时间:2018-05-21 05:31:18

标签: javascript reactjs antd

我想将检查复选框的最大数量限制为3.同时我还想创建所选值的数组。请注意,我使用Ant design's checkbox。代码在codesandbox.io中给出。

handleCheckbox = (e) => {
    let qlen = document.querySelectorAll('input[type="checkbox"]:checked').length;
    if(qlen < 3) {
    if(e.target.checked) {
      this.setState({
        indstryValue: this.state.indstryValue.concat([e.target.value])
      });
    } else {
      var arr = this.state.indstryValue;
      arr = arr.filter(item => item !== e.target.value);
      this.setState({
        indstryValue: arr
      });
    }
  }

  var checks = document.querySelectorAll('input[type="checkbox"]');
  var max = 2;
  for (var i = 0; i < checks.length; i++)
    checks[i].onclick = selectiveCheck;
  function selectiveCheck(event) {
    console.log(event.target);
    var checkedChecks = document.querySelectorAll('input[type="checkbox"]:checked');
    if (checkedChecks.length >= max + 1)
      return false;
  }
}

1 个答案:

答案 0 :(得分:1)

您可以使用反应state来执行此操作。以下示例在选中两个时有条件地禁用复选框。 Codesandbox

import React from "react";
import ReactDOM from "react-dom";
import { Checkbox, Row, Col } from "antd";

class CheckBoxed extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: []
    };
  }
  onChange = checkedValues => {
    this.setState(() => {
      return { checked: checkedValues };
    });
  };

  isDisabled = id => {
    return (
      this.state.checked.length > 1 && this.state.checked.indexOf(id) === -1
    );
  };
  render() {
    return (
      <Checkbox.Group style={{ width: "100%" }} onChange={this.onChange}>
        <Row>
          <Col span={8}>
            <Checkbox value="A" disabled={this.isDisabled("A")}>
              A
            </Checkbox>
          </Col>
          <Col span={8}>
            <Checkbox value="B" disabled={this.isDisabled("B")}>
              B
            </Checkbox>
          </Col>
          <Col span={8}>
            <Checkbox value="C" disabled={this.isDisabled("C")}>
              C
            </Checkbox>
          </Col>
          <Col span={8}>
            <Checkbox value="D" disabled={this.isDisabled("D")}>
              D
            </Checkbox>
          </Col>
          <Col span={8}>
            <Checkbox value="E" disabled={this.isDisabled("E")}>
              E
            </Checkbox>
          </Col>
        </Row>
      </Checkbox.Group>
    );
  }
}

ReactDOM.render(<CheckBoxed />, document.getElementById("container"));