有没有办法在 "React Select" 中的搜索选项中包含组标签

Is there a way to include group label while search options in "React Select"

我已经使用 react-select 允许用户 search/filter 来自选项列表。但是,组标签不包括在搜索中。只是想知道是否有任何方法可以在搜索中包含组标签。

在下面的屏幕截图中,组标签 "COLORECTAL" 及其选项在搜索 "COLOR" 时未显示。

react-select 库不支持开箱即用。您最好的解决方案是要么在回购协议上提出问题以请求此功能,要么分叉回购协议并自己实现此功能。

选择第一个选项会让您处于不确定的位置——功能请求可能永远不会获得批准和实施,或者可能需要几个月的时间。

另一种解决方案让您拥有代码库的所有权以及可能出现的任何现有或未来错误。

您还可以结合这两个选项并在存储库上打开一个功能请求,并包含支持它所需的代码更改。这可能很好,因为您将成为广泛使用的 NPM 包的贡献者。

无论哪种方式,看起来这行代码结合了搜索查询所针对的标签和值:https://github.com/JedWatson/react-select/blob/master/packages/react-select/src/filters.js#L14

我无法为您编写完整的实现,但您需要以某种方式在此字符串中包含组标签,然后找出 UI 以显示 selection 状态对于该组。

我完全同意 Nitsew 的观点。

您可以尝试从 filterOption 道具开始:

const filterOption = ({ label, value }, string) => {
  // default search
  if (label.includes(string) || value.includes(string)) return true;

  // check if a group as the filter string as label
  const groupOptions = groupedOptions.filter(group =>
    group.label.toLocaleLowerCase().includes(string)
  );

  if (groupOptions) {
    for (const groupOption of groupOptions) {
      // Check if current option is in group
      const option = groupOption.options.find(opt => opt.value === value);
      if (option) {
        return true;
      }
    }
  }
  return false;
};

function App() {
  return (
    <div className="App">
      <Select
        defaultValue={colourOptions[1]}
        filterOption={filterOption}
        options={groupedOptions}
      />
    </div>
  );
}

直播Code SandBox example.

if (!string) return true;

您可以在评论默认搜索之前添加此行以处理第一次渲染反应时的默认选项列表-select.