React select 删除搜索中的 selected 选项

React select remove selected option on search

有没有办法始终在菜单上显示所选选项,即使在搜索其他内容后也是如此

这是我使用的代码

import React from "react";
import Select from "react-select/async";
const CheckboxDropdown = ({
  options,
  defaultValue,
  loadOptions,
  handleCheckboxSelect,
}) => {
  const selectDefaultValue = defaultValue;
  
  return (
    <div className="flex">
      <Select
        defaultMenuIsOpen
        defaultOptions={options}
        cacheOptions
        loadOptions={loadOptions}
        options={options}
        defaultValue={defaultValue}
        isMulti
        onChange={handleCheckboxSelect}
        noOptionsMessage={() => "No options available"}
        className="w-full"
        isClearable={false}
        placeholder="Type site name..."
      />
    </div>
  );
};
export default CheckboxDropdown;

试试这个代码吧

const App = () => {
  const [selectedOption, setSelectedOption] = useState();

  const handleChange = (selectedOption) => {
    setSelectedOption(selectedOption);
  }
  const options = [
    { value: 'chocolate', label: 'Chocolate' },
    { value: 'strawberry', label: 'Strawberry' },
    { value: 'vanilla', label: 'Vanilla' },
  ];

  return (
    <div>
      <Select
        isMulti
        hideSelectedOptions={false}
        defaultValue={{ value: 'chocolate', label: 'Chocolate' }} // default value must be like this.
        value={selectedOption} //You forgot pass this  parameter
        onChange={handleChange}
        options={options}
      />
    </div>
  );
}

export default App;

react-select 有一个名为 filterOption 的道具,您可以在其中传递自定义过滤器逻辑。

检查 this CodeSandbox link 以查看我的实现。

import React, { useState } from "react";
import "./styles.css";
import Select from "react-select";

const options = [
  { value: "chocolate", label: "Chocolate" },
  { value: "strawberry", label: "Strawberry" },
  { value: "vanilla", label: "Vanilla" },
  { value: "Apple", label: "apple" },
  { value: "Orange", label: "orange" }
];

export default function App() {
  const [selectedOption, setSelectedOption] = useState([]); //add initial state

  const handleChange = (selectedOption) => {
    setSelectedOption(selectedOption);
  };

  const filterOptions = (candidate, input) => {
    if (input) {
      if (candidate.label.toLowerCase().includes(input.toLowerCase()))
        return true;
      if (
        selectedOption.some((opt) => {
          if (opt.value === candidate.value) return true;
          else return false;
        })
      )
        return true;
      return false;
    }
    return true;
  };

  return (
    <div className="App">
      <Select
        defaultValue={{ value: "chocolate", label: "Chocolate" }} // default value must be like this.
        value={selectedOption}
        onChange={handleChange}
        options={options}
        isMulti
        hideSelectedOptions={false}
        isSearchable
        filterOption={filterOptions}
      />
    </div>
  );
}