reactjs - 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 },
];
解决方案
您可以在组件中使用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;
}
};
推荐阅读
- java - 无法最小化 Process.Start 上的新进程窗口
- angular - 如果 Angular 9 中不存在子组件,如何在父元素上设置 display:none?
- vb.net - MovePrevious 从填充的标签中删除文本
- mysql - 我有一个较旧的 .sql 文件(从 5.0.45 导出)我正在尝试通过 phpMyAdmin 导入到较新版本的 MySQL 中。接收错误
- php - 日期显示错误
- arduino - 让两个 arduino 交互而不将它们连接在一起
- typescript - 使用 rxjs 时出错 - 管道和点击运算符
- java - 从 Excel 中读取数值时出现问题
- ios - Xcode 11.4 中 Swift 4 或 5 中的 CircularSpinner 版本
- typescript - 在 Typescript 中声明任何与显式类型哪个具有更好的性能