在 react-select 中排序搜索结果

Order search results in react-select

使用react-select时,搜索结果默认按字母顺序排列。这是一个很好的默认值,但如果我有一个不是按字母顺序排列的完全匹配,那就不太好了。例如,用户可能有以下选项:

使用这些选项,用户可以搜索 'react' 而不是更接近于选择与搜索词完全匹配的选项。有什么方法可以针对精确匹配进行优化吗?

react-select 中,您可以传递 filterOption 属性 来更改过滤的工作方式。他们提供了一个很好的 api 来做你想做的事情,这是从字符串的开头而不是字符串中的任何地方开始匹配。看起来像这样

filterOption={createFilter({ matchFrom: "start" })}

其中 createFilter 是从 react-select

导入的

react-select 如果您想拥有自定义过滤器,则有一个道具 - filterOption.

如果您想根据用户查询显示更好的匹配项,请使用 match-sorter in combination with onInputChange of react-select to create a custom filter. Here's a working demo

有两个 select 输入。输入 l 并观察建议的差异。

@ron4ex 在这里有一个很好的答案。只是想提供另一个类似的解决方案,因为我在 match-sorter.

中遇到了一个大问题

match-sorter 的问题:

  • 我的列表是家庭关系的列表,例如“妈妈”,“mother-in-law”
  • 当我开始打字时,
  • match-sorter 会优先 mother-in-law 而不是妈妈。只有完全匹配后,它才会优先考虑母亲。但是,react-select 将焦点选项保留为 mother-in-law。
  • 即使我可以解决默认焦点问题,我也宁愿在“mother-in-law”之前“mot”匹配“mother”。

输入新的解决方案:Fuse:

  • 与match-sorter
  • 类似的实现
  • 具有大量自定义选项的模糊搜索
  • 默认配置将“母亲”排序为“mother-in-law”
const fuse = new Fuse(relationshipTypes, { keys: ["label"] });

<Select>
  onInputChange={inputValue => {
    setRelationshipOptions(
      fuse.search(inputValue).map(value => value.item)
    );
  }}
</Select>
  • 注意 fuse.search 上的映射作为融合 returns 一个变异的数组,原始值在项目键中,第二个键是索引。因此,fuse.search().map