Material-UI 自动完成总是显示指定的项目

Material-UI Autocomplete always show specified items

有没有办法让 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 },
];

您可以在 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;
    }
  };