簡體   English   中英

如果在反應 select 中選擇了 label / 值,如何過濾?

[英]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時,該值將是一個選定項目的數組。

請參閱我創建的此代碼沙箱。

https://codesandbox.io/s/quiet-butterfly-vfxwi

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM