【问题标题】:Material Ui Autocomplete - Filtering options is not working as expectedMaterial Ui 自动完成 - 过滤选项未按预期工作
【发布时间】:2021-09-15 18:14:30
【问题描述】:

我有自动完成功能,我在其中传递了一组已获取和预定义的选项... https://codesandbox.io/s/geocoding-demo-forked-2f189?file=/src/App.js

当我输入例如“Diestsestraat Leuven”它不显示任何选项,但是当我 console.log 它时,我看到了一系列选项。

但它不会过滤掉预定义的选项(见截图)

有什么建议吗?

【问题讨论】:

    标签: reactjs autocomplete material-ui


    【解决方案1】:

    所以在filterOptions 上,您只返回应该过滤的选项。 您可以尝试添加:

    filterOptions={(options) =>
      options.filter(({ place_name }) => place_name.includes(query))
    }
    

    【讨论】:

    • 当你输入 - “Diestsestraat Leuven” - 它不显示任何选项,但是当我 console.log 它时,我看到了一系列选项。
    • 我提供了操场的链接,所以你可以看到自己...
    • 唯一可用的选项是Diestsestraat, Leuven - 请注意,
    【解决方案2】:

    您可以在 Autocomplete 组件中使用 filterOptions 属性。它为您提供 2 个参数。第一个是你给它的选项,第二个是输入组件的状态。因此,您可以使用自己的过滤器对其进行自定义:

    const filterOptions = (options, state) => {
        let newOptions = [];
        options.forEach((element) => {
          if (
            element.place_name
              .replace(",", "")
              .toLowerCase()
              .includes(state.inputValue.toLowerCase())
          )
            newOptions.push(element);
        });
        return newOptions;
      };
    

    【讨论】:

    • 这是一个要检查的搜索词 - Diestsestraat Leuven
    • @Nikita 更新了答案。请检查。这是因为 options 在术语中有,,您需要将其删除!
    • 不确定这是最好的解决方案 - .replace(",", "")....
    • @Nikita 所以你需要用这个词来实现你的目标:Diestsestraat, Leuven!
    • 请查看此链接:https://appdividend.com/2020/08/01/javascript-remove-character-from-string-example/replace 是从字符串中删除字符的解决方案之一。
    猜你喜欢
    • 1970-01-01
    • 2020-12-17
    • 2020-08-09
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 2011-05-22
    相关资源
    最近更新 更多