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

如何配置MUI Autocomplete实现输入3字符后显示匹配建议?

解决方案

要实现输入至少3个字符才显示匹配建议,可以通过以下两种方式处理:

方式一:前端过滤已获取的数据

适合数据量较小的场景,利用Autocomplete的filterOptions属性控制过滤逻辑:

修改后的完整代码

import TextField from '@mui/material/TextField';
import Stack from '@mui/material/Stack';
import Autocomplete from '@mui/material/Autocomplete';
import { useEffect, useState } from 'react';
import { Box } from '@mui/system';

export default function Demo() {
  const url = 'https://www.balldontlie.io/api/v1/players'
  const [jsonResult, setJsonResult] = useState([]);
  
  useEffect(()=>{
    fetch(url)
      .then((res) => res.json())
      .then((json)=> setJsonResult(json.data));
  },[]);

  // 自定义过滤逻辑
  const filterOptions = (options, { inputValue }) => {
    // 输入长度小于3时返回空数组,不显示建议
    if (inputValue.trim().length < 3) {
      return [];
    }
    // 输入长度达标时,使用Material UI默认的过滤逻辑
    return Autocomplete.defaultProps.filterOptions(options, { inputValue });
  };

  return (
    <Stack spacing={2} sx={{width:300}}>
      <Autocomplete
        id="free-solo-demo"
        freeSolo
        // 修正参数命名,避免和状态变量冲突
        getOptionLabel={(option)=> `${option.first_name} ${option.last_name}`}
        options={jsonResult}
        isOptionEqualToValue={(option,value)=>
          option.first_name === value.first_name
        }
        noOptionsText="No Match Found"
        // 应用自定义过滤逻辑
        filterOptions={filterOptions}
        renderOption={(props, option)=>(
          <Box component="li" {...props} key={option.id}>
            {option.first_name} {option.last_name}
          </Box>
        )}
        renderInput={(params)=> 
          <TextField {...params} label="Player search"/>
        }
      /> 
    </Stack>
  );
}

关键说明

  • filterOptions函数:接收原始选项和输入值,当输入字符数不足3时返回空数组,直接隐藏建议列表;达标后调用默认过滤逻辑匹配选项。
  • 修正了getOptionLabel和renderOption的参数命名(从jsonResult改为option),避免和状态变量重名导致的混淆。

方式二:按需请求API(推荐,适合大数据量)

如果球员数据量很大,一次性加载所有数据会影响性能,建议只在输入≥3个字符时才发起API请求:

修改后的代码

import TextField from '@mui/material/TextField';
import Stack from '@mui/material/Stack';
import Autocomplete from '@mui/material/Autocomplete';
import { useEffect, useState } from 'react';
import { Box } from '@mui/system';

export default function Demo() {
  const url = 'https://www.balldontlie.io/api/v1/players'
  const [jsonResult, setJsonResult] = useState([]);
  const [inputValue, setInputValue] = useState('');

  // 当输入值变化且长度≥3时,发起API请求
  useEffect(()=>{
    if (inputValue.trim().length < 3) {
      setJsonResult([]);
      return;
    }
    // 利用API的search参数按名字查询,减少返回数据量
    fetch(`${url}?search=${inputValue}`)
      .then((res) => res.json())
      .then((json)=> setJsonResult(json.data));
  },[inputValue]);

  return (
    <Stack spacing={2} sx={{width:300}}>
      <Autocomplete
        id="free-solo-demo"
        freeSolo
        getOptionLabel={(option)=> `${option.first_name} ${option.last_name}`}
        options={jsonResult}
        isOptionEqualToValue={(option,value)=>
          option.first_name === value.first_name
        }
        noOptionsText="No Match Found"
        // 监听输入值变化,更新状态
        onInputChange={(event, newInputValue) => {
          setInputValue(newInputValue);
        }}
        renderOption={(props, option)=>(
          <Box component="li" {...props} key={option.id}>
            {option.first_name} {option.last_name}
          </Box>
        )}
        renderInput={(params)=> 
          <TextField {...params} label="Player search"/>
        }
      /> 
    </Stack>
  );
}

关键说明

  • 用inputValue状态跟踪用户输入,只有当输入长度≥3时才调用API,同时清空之前的结果。
  • 利用API自带的search参数精准查询,减少不必要的数据传输,提升页面性能。

内容的提问来源于stack exchange,提问作者innkiddo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 21:50:38