Material-UI <Autocomplete /> 按多个参数搜索

3

我开始学习 Material UI,有一个问题。

我们有一个对象

const top100Films = [
  { label: 'The Shawshank Redemption', year: 1994 },
  { label: 'The Godfather', year: 1972 }, 

  * ...More items *
]

现在,如果我在我的自动完成中设置getOptionLabel = {option => option.label},它只会通过匹配标签(标题)进行搜索,因此如果我输入一个年份,例如“1994”,它不会在我的搜索结果中显示“肖申克的救赎”,如果我将其设置为option.year,它只会按年份搜索,任何非年份的输入都将无效。

我的问题是:有没有办法设置它,以便我可以通过标题或年份进行搜索。

解决方案:

<Autocomplete
  ...
  filterOptions={(options, { inputValue }) => options.filter(item => item.label.toLowerCase().includes(inputValue) || item.year.toString().includes(inputValue) )}
/>

https://mui.com/components/autocomplete/#custom-filter - Brian Thompson
1个回答

2
MUI自动完成API有一个filterOptions(这里的文档)属性,您可以设置自定义过滤器。
我会这样实现:
<Autocomplete
  ...
  filterOptions={(options, { inputValue }) => options.filter(item => item.label.includes(inputValue) || item.year.toString.includes(inputValue) )}
/>

1
通过小的调整,您的建议非常好!谢谢!只需要为标题添加转换为小写即可。 - ENE
还添加了.toLowerCase()到两边,以便搜索不区分大小写。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接