React-select用户选择后如何清除选项 [英] React-select How to clear options once user selected
问题描述
我正在使用react-select向用户显示选项的下拉列表.我希望如果选择了特定选项,其他所有选项都将消失.
I'm using react-select to present the user with a dropdown list of options. I would like it if a specific option is chosen, all other options will disappear.
例如,如果选择了全部"选项,我希望所有其他选项消失:
For example, if the "ALL" option is selected, I would like all other options to disappear:
据我所知,react-select保持未选择选项的状态.可以通过传递给react-select组件的一些道具来控制它吗?
As far as I saw, react-select maintains the state of the non-selected options. Can this be controlled via some prop passed to the react-select component?
推荐答案
您可以在handler
中编写相关的进程,如果选择了all
,则仅将option data
更改为项目all
.如果清除选择,请恢复原始的option data
.
You can write related processes in handler
, if all
is selected, change the option data
to the item all
only. If selection cleared, restore the original 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>
</>
);
}
}
在线尝试:
这篇关于React-select用户选择后如何清除选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!