【问题标题】:Material UI Autocomplete - Search only from the beginning of the wordMaterial UI 自动完成 - 仅从单词的开头搜索
【发布时间】:2020-06-11 15:23:02
【问题描述】:

我在我的 React 应用程序中使用 Material UI Autocomplete 字段,我希望其中的搜索仅从关键字的开头开始工作(对于对象的某些字段):

例如,如果选项是

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

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

【问题讨论】:

    标签: reactjs search autocomplete material-ui


    【解决方案1】:

    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】:

    使其与 filterOptions Autocomplete 道具和 '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',
          ],
        });
    

    【讨论】:

      【解决方案3】:

      我想添加一些关于过滤的额外信息。您还可以使用 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' [可选])
      • 字符串化(Func [可选])
      • 修剪(布尔 [可选])

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

      希望这可以帮助某人!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多