[英]how to filter if label / value has been selected in react select?
how to filter if label / value has been selected in react select?如果在反应 select 中选择了 label / 值,如何过滤?
first I have a list of options (from the API) as follows:首先,我有一个选项列表(来自 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'}
];
Then I want if one of the labels / values that I have selected does not appear in the listFoodSelect, for example, I select foodID 234, how do I filter the list if the label / value has been selected?然后我想如果我选择的标签/值之一没有出现在listFoodSelect中,例如,我select foodID 234,如果选择了label/值,我该如何过滤列表?
expectations are as follows:期望如下:
const listFoodSelect = [
{foodID: 123, label: 'food 1'},
{foodID: 456, label: 'food 2'},
{foodID: 789, label: 'food 3'},
{foodID: 321, label: 'food 4'},
];
this is a initial state这是一个初始 state
const [menuName, setMenuName] = useState('')
const [listFoodSelect, setListFoodSelect] = useState([])
This is a function to adjust if the value is selected这是一个 function 调整如果值被选中
const onSelectMenu = (indexItem, indexFood) => event => {
let { foodId, label } = event
let data = [...listData]
setMenuName(event.label)
setListFoodSelect(listFoodSelect.filter(item => item.foodName !== label))
}
and this is the react-select component that has been returned这是已经返回的 react-select 组件
<Select
onChange={onSelectMenu(indexItem, indexFood)}
options={listFoodSelect.filter((option) => option.label !== menuName)}
value={menuName}
/>
See this codesandbox I have created.请参阅我创建的这个代码框。 Let me know if you have questions
如果您有任何问题,请告诉我
https://codesandbox.io/s/wispy-violet-yv5yt?file=/src/App.jshttps://codesandbox.io/s/wispy-violet-yv5yt?file=/src/App.js
You should use isMulti
prop.你应该使用
isMulti
道具。 It allows you to select more than one item.它允许您 select 不止一项。 Once an item is selected, it will be removed from the list of the select dropdown menu.
一旦选择了一个项目,它将从 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>
);
}
When isMulti
prop is used, the value will be an array of selected items.当使用
isMulti
时,该值将是一个选定项目的数组。
See this code sandbox I have created.请参阅我创建的此代码沙箱。
https://codesandbox.io/s/quiet-butterfly-vfxwi https://codesandbox.io/s/quiet-butterfly-vfxwi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.