gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:02:39 46 4
gpt4 key购买 nike

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

例如,如果选择“ALL”选项,我希望所有其他选项消失: enter image description here

据我所知,react-select 维护未选定选项的状态。这可以通过传递给react-select组件的一些 Prop 来控制吗?

最佳答案

可以在handler中编写相关流程,如果all选中后,更改 option data到该项目all仅有的。如果清除选择,则恢复原始 option data .

<小时/>

enter image description here

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>
</>
);
}
}

在线尝试:

Edit bold-shannon-dk59l

关于javascript - React-select 用户选择后如何清除选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60616545/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com