启用 React-Select 选项以在搜索过程中保留?

问题描述 投票:0回答:1

我试图使我的反应选择组件中的第一个和最后一个选项始终显示在列表中。我不希望它在搜索过程中被过滤掉。有没有办法消除某个项目被过滤?我尝试过自定义过滤器,请参阅codesandbox link,但它不起作用。如果我搜索不在第一项或最后一项中的 或 字母,它将被删除。有人可以提供任何帮助吗?请参阅下面的相关片段:

    const customFilter = (option, rawInput) => {
    const inputValue = rawInput.toLowerCase();

    // If there's no input, include all options
    if (!inputValue) {
      return true;
    }

    // Allow the first and last options to always be visible
    if (option.index === 0 || option.index === options.length - 1) {
      return true;
    }

    // Apply regular filtering for other options
    return (
      option.label.toLowerCase().includes(inputValue) ||
      option.value.toLowerCase().includes(inputValue)
    );
  };

  return (
    <>
      <Select
        options={options}
        isSearchable={true}
        filterOption={customFilter}
      />
    </>
  );
};
reactjs react-select react-select-search
1个回答
0
投票

import Select from 'react-select';


function App() {
  const options = [
    { value: 'first', label: 'first', fixed: true },
    { value: 'chocolate', label: 'Chocolate' },
    { value: 'strawberry', label: 'Strawberry' },
    { value: 'vanilla', label: 'Vanilla' },
    { value: 'last', label: 'last', fixed: true },
  ]

  const customFilter = (option, rawInput) => {
    const inputValue = rawInput.toLowerCase();

    // If there's no input, include all options
    if (!inputValue) {
      return true;
    }

    // Allow the first and last options to always be visible
    if (option.data.fixed) {
      console.log("from option fixed ====>", option);
      return true;
    }

    // Apply regular filtering for other options
    return (
      option.label.toLowerCase().includes(inputValue) ||
      option.value.toLowerCase().includes(inputValue)
    );
  }

  return (
    <div className="App">
      <Select
        options={options}
        isSearchable={true}
        filterOption={customFilter}
      />
    </div>
  );
}

export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

这是如何修复第一个和最后一个项目的示例。

说明: 如果您检查 options 数组,您将看到一个名为 fixed 的键。如果 fixed 为 true,那么无论如何这些项目都会显示。您只需将 fixed 添加为 true 选项的第一项和最后一项或您想要修复的任何一项。

希望这有帮助。如果您有任何疑问,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.