【问题标题】:how to filter if label / value has been selected in react select?如果在反应选择中选择了标签/值,如何过滤?
【发布时间】:2021-05-11 06:07:03
【问题描述】:

如果在反应选择中选择了标签/值,如何过滤?

首先我有一个选项列表(来自 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中,例如我选择foodID 234,如果标签/值已经被选择,我该如何过滤列表?

预期如下:

const listFoodSelect = [
   {foodID: 123, label: 'food 1'},
   {foodID: 456, label: 'food 2'},
   {foodID: 789, label: 'food 3'},
   {foodID: 321, label: 'food 4'},
];

这是一个初始状态

const [menuName, setMenuName] = useState('')
const [listFoodSelect, setListFoodSelect] = useState([])

如果选择了值,这是一个调整功能

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

【问题讨论】:

  • 当用户选择一个选项时,您想删除所有其他选项吗?
  • 不,我想如果用户选择一个选项,那么只有选定的选项不会出现
  • 那么你做错了什么?
  • 列表选项保持未经过滤
  • 看我的回答希望它是你想要的

标签: javascript reactjs react-hooks react-select


【解决方案1】:

查看我创建的这个代码框。如果您有任何问题,请告诉我

https://codesandbox.io/s/wispy-violet-yv5yt?file=/src/App.js

【讨论】:

  • 非常感谢,这已经开始了我的期望但是缺少一些东西,如果值是一个数组,如何过滤它?
【解决方案2】:

你应该使用isMulti 属性。它允许您选择多个项目。一旦选择了一个项目,它将从选择下拉菜单的列表中删除。

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

【讨论】:

    猜你喜欢
    • 2019-02-08
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    相关资源
    最近更新 更多