Material-UI Autocomplete组件如何固定展示指定选项不受搜索匹配影响
Material-UI Autocomplete固定展示指定选项的实现方法
你可以通过自定义Autocomplete组件的filterOptions属性实现需求,核心逻辑是在默认搜索匹配结果的基础上,额外加入所有标记了alwaysShow: true的选项,再做去重处理避免重复展示。
具体修改步骤
- 引入默认过滤器创建工具
import { createFilterOptions } from '@material-ui/lab/Autocomplete';
- 自定义过滤逻辑:保留默认搜索匹配结果,同时加入所有固定展示的选项
// 生成默认过滤器实例 const defaultFilter = createFilterOptions(); // 自定义过滤函数 const customFilter = (options, filterParams) => { // 获取默认匹配搜索内容的选项 const matchedOptions = defaultFilter(options, filterParams); // 筛选所有需要固定展示的选项 const pinnedOptions = options.filter(item => item.alwaysShow); // 合并数组后去重返回 return [...new Set([...pinnedOptions, ...matchedOptions])]; }
- 将自定义过滤函数传入Autocomplete组件的对应属性
<Autocomplete {...defaultProps} filterOptions={customFilter} renderInput={(params) => ( <TextField {...params} label="movies" margin="normal" /> )} />
修改后完整示例代码
import React from "react"; import TextField from "@material-ui/core/TextField"; import Autocomplete, { createFilterOptions } from "@material-ui/lab/Autocomplete"; const defaultFilter = createFilterOptions(); const customFilter = (options, filterParams) => { const matchedOptions = defaultFilter(options, filterParams); const pinnedOptions = options.filter(item => item.alwaysShow); return [...new Set([...pinnedOptions, ...matchedOptions])]; }; export default function Playground() { const defaultProps = { options: top100Films, getOptionLabel: (option) => option.title }; return ( <div style={{ width: 300 }}> <Autocomplete {...defaultProps} filterOptions={customFilter} 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 }, ];
如果使用的是MUI v5版本,仅需将导入路径替换为@mui/material/Autocomplete即可,逻辑完全通用。
内容的提问来源于stack exchange,提问作者wolf_math
相关产品推荐
相关产品推荐

