React-select 如何在用户选择后清除选项

IT技术 javascript html reactjs jsx react-select
2021-05-16 13:50:29

我正在使用 react-select 向用户显示选项下拉列表。我希望如果选择了特定选项,所有其他选项都将消失。

例如,如果选择了“ALL”选项,我希望所有其他选项都消失: 在此处输入图片说明

就我所见, react-select 保持未选中选项的状态。这可以通过传递给 react-select 组件的一些props来控制吗?

1个回答

您可以在 中写入相关流程handler,如果all选中,则更option data改为all项目如果选择清除,则恢复原始option data.


在此处输入图片说明

import React from "react";
import "./styles.css";
import Select from "react-select";

const data = [
  { value: "1", label: "1" },
  { value: "2", label: "2" },
  { value: "3", label: "3" },
  { value: "4", label: "all" }
];
export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedLabel: "",
      selectedLabelList: []
    };
  }
  singleHandler = e => {
    this.setState({ selectedLabel: e ? e.label : "" });
  };
  multiHandler = e => {
    this.setState({
      selectedLabelList: e && e.length > 0 ? e.map(x => x.label) : []
    });
  };
  render() {
    const { selectedLabel, selectedLabelList } = this.state;
    const subListWithAll = data.filter(x => x.label === "all");
    const singleOptions = selectedLabel === "all" ? subListWithAll : data;
    const multiOptions = selectedLabelList.includes("all")
      ? subListWithAll
      : data;
    return (
      <>
        <div>
          <Select
            id="single"
            isClearable={true}
            value={singleOptions.filter(x => x.label === selectedLabel)}
            options={singleOptions}
            onChange={this.singleHandler}
          />
        </div>
        <div>
          <Select
            id="multi"
            isMulti
            isClearable={true}
            value={multiOptions.filter(x =>
              selectedLabelList.includes(x.label)
            )}
            options={multiOptions}
            onChange={this.multiHandler}
          />
        </div>
      </>
    );
  }
}

在线试一下:

编辑粗体香农 dk59l