[英]how to filter if label / value has been selected in react select?
如果在反应 select 中选择了 label / 值,如何过滤?
首先,我有一个选项列表(来自 API),如下所示:
const listFoodSelect = [
{foodID: 123, label: 'food 1'},
{foodID: 456, label: 'food 2'},
{foodID: 789, label: 'food 3'},
{foodID: 321, label: 'food 4'},
{foodID: 234, label: 'food 5'}
];
然后我想如果我选择的标签/值之一没有出现在listFoodSelect中,例如,我select foodID 234,如果选择了label/值,我该如何过滤列表?
期望如下:
const listFoodSelect = [
{foodID: 123, label: 'food 1'},
{foodID: 456, label: 'food 2'},
{foodID: 789, label: 'food 3'},
{foodID: 321, label: 'food 4'},
];
这是一个初始 state
const [menuName, setMenuName] = useState('')
const [listFoodSelect, setListFoodSelect] = useState([])
这是一个 function 调整如果值被选中
const onSelectMenu = (indexItem, indexFood) => event => {
let { foodId, label } = event
let data = [...listData]
setMenuName(event.label)
setListFoodSelect(listFoodSelect.filter(item => item.foodName !== label))
}
这是已经返回的 react-select 组件
<Select
onChange={onSelectMenu(indexItem, indexFood)}
options={listFoodSelect.filter((option) => option.label !== menuName)}
value={menuName}
/>
请参阅我创建的这个代码框。 如果您有任何问题,请告诉我
https://codesandbox.io/s/wispy-violet-yv5yt?file=/src/App.js
你应该使用isMulti
道具。 它允许您 select 不止一项。 一旦选择了一个项目,它将从 select 下拉菜单的列表中删除。
import React, { useState } from "react";
import Select from "react-select";
import "./styles.css";
export default function App() {
const listFoodOptions = [
{ value: 123, label: "food 1" },
{ value: 456, label: "food 2" },
{ value: 789, label: "food 3" },
{ value: 321, label: "food 4" },
{ value: 234, label: "food 5" }
];
const [selectedFoods, setSelectedFoods] = useState([]);
const handleSelect = (newlySelectedFoods) => {
setSelectedFoods(newlySelectedFoods);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<Select
onChange={handleSelect}
options={listFoodOptions}
isMulti
value={selectedFoods}
/>
</div>
);
}
当使用isMulti
时,该值将是一个选定项目的数组。
请参阅我创建的此代码沙箱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.