如何自定义反应选择设置搜索过滤器

dev*_*Dev 4 react-select

const ItemOptions: SelectValueInterface[] = Item.map((e) => ({
  value: e.ItemId,
  label: `${e.ItemName} (Item ID : ${e.ItemId})`,
}));
const options = [
  {
    label: 'ITEM NAME (Item ID)',
    options: ItemOptions,
  },
];

const formatGroupLabel = (data: any) => (
  <div className={styles.formatGroupLabel}>
    <span>{data.label}</span>
  </div>
);

<Select
  placeholder="Select Name"
  options={options}
  formatGroupLabel={formatGroupLabel}
  classNamePrefix="select-list"
  value={ItemOptions.filter((option) => option.value === selectedItemId)}
  onChange={filterByItemID}
/>;
Run Code Online (Sandbox Code Playgroud)

当我输入搜索/排序时,Item ID它会显示所有选项。我想不检测(Item ID: number)

K. *_*ikh 5

以下是我如何使用此道具自定义 DropDown 过滤器 - filterOption={customFilter}

import React, { Component, useState } from "react";
import Select from "react-select";
import DropDownOptions from "./DropDownOptions";
import DropDownValueContainer from "./DropDownValueContainer";
import "./DropDown.less";

const DropDown = () => {
  const options = [
    { value: "value1", label: "Header1" },
    { value: "value2", label: "Header2" },
    { value: "value3", label: "Header3" },
  ];
  const [selectedValue, setSelectedValue] = useState({});
  const handleChange = (selectedOption) => {
    setSelectedValue(selectedOption);
  };

  const colourStyles = {
    valueContainer: (base, state) => ({
      ...base,
      backgroundColor: state.isSelected ? "red" : "white",
    }),
    input: (base, state) => ({
      ...base,
      display: state.selectProps.menuIsOpen ? "block" : "none,"
    })
  };

  //Add your search logic here.
  const customFilter = (option, searchText) => {
    if (
      option.data.label.toLowerCase().includes(searchText.toLowerCase()) ||
      option.data.value.toLowerCase().includes(searchText.toLowerCase())
    ) {
      return true;
    } else {
      return false;
    }
  };

  return (
    <Select
      placeholder="Select Value"
      options={options}
      defaultValue={options[0]}
      onChange={handleChange}
      components={{
        Option: DropDownOptions,
        ValueContainer: DropDownValueContainer,
      }}
      isSearchable={true}
      styles={colourStyles}
      filterOption={customFilter}
      classNamePrefix="dropdownStyles"
    />
  );
};

export default DropDown;
Run Code Online (Sandbox Code Playgroud)

通过这篇文章来理解代码