首页 > 解决方案 > Material-UI 自动完成总是显示指定的项目

问题描述

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

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 },
];

标签: reactjsautocompletematerial-ui

解决方案


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

  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;
    }
  };

编辑可疑-darwin-f99hs


推荐阅读