You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Material-UI Autocomplete组件如何固定展示指定选项不受搜索匹配影响

Material-UI Autocomplete固定展示指定选项的实现方法

你可以通过自定义Autocomplete组件的filterOptions属性实现需求,核心逻辑是在默认搜索匹配结果的基础上,额外加入所有标记了alwaysShow: true的选项,再做去重处理避免重复展示。

具体修改步骤

  1. 引入默认过滤器创建工具
import { createFilterOptions } from '@material-ui/lab/Autocomplete';
  1. 自定义过滤逻辑:保留默认搜索匹配结果,同时加入所有固定展示的选项
// 生成默认过滤器实例
const defaultFilter = createFilterOptions();
// 自定义过滤函数
const customFilter = (options, filterParams) => {
  // 获取默认匹配搜索内容的选项
  const matchedOptions = defaultFilter(options, filterParams);
  // 筛选所有需要固定展示的选项
  const pinnedOptions = options.filter(item => item.alwaysShow);
  // 合并数组后去重返回
  return [...new Set([...pinnedOptions, ...matchedOptions])];
}
  1. 将自定义过滤函数传入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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 16:00:02