【问题标题】:Material-UI Autocomplete always show specified itemsMaterial-UI 自动完成总是显示指定的项目
【发布时间】:2021-09-14 10:15:16
【问题描述】:

有没有办法让 Material-UI 的自动完成中的项目始终显示,无论是否匹配?例如,在下面的 Shawshank Redemption 下,我添加了一个 alwaysShow 密钥对。如果我开始输入“低俗小说”,我还希望 Shawshank Redemption 显示。

import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";

export default function Playground() {
  const defaultProps = {
    options: top100Films,
    getOptionLabel: (option) => option.title
  };

  return (
    <div style={{ width: 300 }}>
      <Autocomplete
        {...defaultProps}
        renderInput={(params) => (
          <TextField {...params} label="movies" margin="normal" />
        )}
      />
    </div>
  );
}

const top100Films = [
  { title: "The Shawshank Redemption", year: 1994, alwaysShow: true },
  { title: "The Godfather", year: 1972 },
  { title: "12 Angry Men", year: 1957 },
  { title: "Pulp Fiction", year: 1994 },
  { title: "The Good, the Bad and the Ugly", year: 1966 },
  { title: "3 Idiots", year: 2009 },
];

【问题讨论】:

    标签: reactjs autocomplete material-ui


    【解决方案1】:

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

      const defaultProps = {
        options: top100Films,
        getOptionLabel: (option) => option.title,
        filterOptions: (options, state) => {
          let newOptions = [];
          options.forEach((element) => {
            if (element.title.includes(state.inputValue)) newOptions.push(element);
          });
          options.forEach((element) => {
            if (element.alwaysShow) newOptions.push(element);
          });
          return newOptions;
        }
      };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-04
      • 2020-09-18
      • 2021-11-17
      • 1970-01-01
      相关资源
      最近更新 更多