gpt4 book ai didi

reactjs - 如何从 React Select 选项中排除某些选项

转载 作者:行者123 更新时间:2023-12-02 01:36:51 28 4
gpt4 key购买 nike

我有大约 50 个选项要显示在 react 选择选项中。但我想排除一些与已发布的值具有逻辑的选项。目的是,我们有一个表单,可以从下拉列表中添加值。如果添加了一项,则不必将其显示在下拉列表中。

重构代码:

export default function App() {
const choices = [
{
value: 0,
label: "Container empty to shipper"
},
{
value: 1,
label: "Container pickup at shipper"
},
{
value: 2,
label: "Container arrival at first POL (Gate in)"
},
{
value: 3,
label: "Container loaded at first POL"
}
];

const postedList = [
"Container empty to shipper",
"Container pickup at shipper"
];
return (
<div className="App">
<h1>Select Box</h1>
<Select
isClearable={false}
// here the choices should be 2 eliminating the other 2 whose labels are matching to postedlist
options={choices}
defaultValue={choices[0]}
onChange={(choice) => console.log(choice.value)}
/>
</div>
);
}

目前,它正在呈现所有 4 个可用选项,但我只想返回其中 2 个标签与 postedlist 不匹配的选项

我还创建了 Codesandbox 。如果你想在那里看到它。

最佳答案

您可以使用Array.prototype.filter()Array.prototype.includes()过滤掉已经发布的项目。然后使用 filteredList 作为 Select 组件的输入,如下所示。

  const filteredList = choices.filter(({ label }) =>
!postedList.includes(label)
);

return (
<div className="App">
<h1>Select Box</h1>
<Select
isClearable={false}
options={filteredList}
defaultValue={filteredList[0]}
onChange={(choice) => console.log(choice.value)}
/>
</div>
);

Edit happy-wave-yktw2j

关于reactjs - 如何从 React Select 选项中排除某些选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72242254/

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