React Select Multi Select复选框-带全选

时间:2019-05-07 07:20:03

标签: reactjs react-select

我正在寻找一些具有多选复选框功能以及全选选项的React组件,我可以看到很少的组件,但没有选择所有内置的Feature。有指针吗?

1 个答案:

答案 0 :(得分:0)

基本上,您需要使用受控的valueonChange道具。以及复选框上的OnChange

以下一种实现方法:

import React, { Component } from "react";
import ReactDOM from "react-dom";
import Select from "react-select";
import "./styles.css";

const options = [
  { label: "Option 1", value: 1 },
  { label: "Option 2", value: 2 },
  { label: "Option 3", value: 3 },
  { label: "Option 4", value: 4 },
  { label: "Option 5", value: 5 },
  { label: "Option 6", value: 6 },
  { label: "Option 7", value: 7 }
];
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: false,
      values: []
    };
  }
  onChangeCheckbox = e => {
    const isChecked = !this.state.checked;
    this.setState({
      checked: isChecked,
      values: isChecked ? options : this.state.values
    });
  };
  onChange = opt => {
    const allOptionsSelected = opt.length === options.length;
    this.setState({
      checked: allOptionsSelected ? true : false,
      values: opt
    });
  };
  render() {
    return (
      <div className="App">
        <Select
          isMulti
          onChange={this.onChange}
          options={options}
          value={this.state.values}
        />
        <p>
          <input
            onChange={this.onChangeCheckbox}
            type="checkbox"
            id="selectAll"
            value="selectAll"
            checked={this.state.checked}
          />
          <label for="selectAll">Select all</label>
        </p>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

这里是live example