材质用户界面自动完成-仅从单词开头搜索

时间:2020-02-27 15:05:54

标签: reactjs search autocomplete material-ui

我在React应用程序中使用了实质性的UI自动完成字段,并且我希望其中的搜索仅从关键字的开头(对于对象的某些字段)起作用:

例如,如果选项为

[
  {data1:'abc', data2:'a123'},
  {data1:'cba', data2:'345'},
  {data1:'bca3', data2:'654'}
]

,然后输入a-仅出现第一个选项。 如果我输入3-仅第二个选项应该出现。

3 个答案:

答案 0 :(得分:1)

使其与filterOptions自动完成道具和'match-sorter'库一起使用:

const filterOptions = (options,{ inputValue }) =>
    matchSorter(options, inputValue, {
      keys: [
        { threshold: matchSorter.rankings.STARTS_WITH, key: 'data1' },
        { threshold: matchSorter.rankings.STARTS_WITH, key: 'data2' },
        'data3',
      ],
    });

答案 1 :(得分:0)

https://material-ui.com/components/autocomplete/#multiple-values

有效, 您需要添加 多个

  <Autocomplete
    multiple
    id="tags-standard"
    options={top100Films}
    getOptionLabel={option => option.title}
    defaultValue={[top100Films[13]]}
    renderInput={params => (
      <TextField
        {...params}
        variant="standard"
        label="Multiple values"
        placeholder="Favorites"
      />
    )}
  />

答案 2 :(得分:0)

我想添加一些有关过滤的额外信息。您还可以使用MUI自动完成功能提供的createFilterOptions

示例:

import { createFilterOptions } from '@material-ui/lab/Autocomplete';

const filterOptions = createFilterOptions({
  matchFrom: 'start',
  stringify: option => option.title,
});

<Autocomplete filterOptions={filterOptions} />

您可以设置一些可选的过滤器:

  • ignoreAccents(布尔值[可选])
  • ignoreCase(布尔值[可选])
  • 限制(数字[可选])
  • matchFrom('any'|'start'[可选])
  • stringify(功能[可选])
  • trim(布尔值[可选])

https://material-ui.com/components/autocomplete/

希望这可以帮助某人!