MUI 5 自动完成筛选选项计数

MUI 5 Autocomplete filtered options count

如何从 MUI 5 Autocomplete 组件中获取筛选选项的计数? (不改变 prop filterOptions 的默认行为)

您可以创建 filterOptions 回调的包装器,方法是使用 createFilterOption 创建内部使用的默认值,例如 the one,并添加您的附加代码以检查结果长度:

import Typography from '@mui/material/Typography';
import TextField from '@mui/material/TextField';
import Autocomplete, { createFilterOptions } from '@mui/material/Autocomplete';

const _filterOptions = createFilterOptions();

export default function ComboBox() {
  const [optionCount, setOptionCount] = React.useState(0);
  const filterOptions = React.useCallback((options, state) => {
    const results = _filterOptions(options, state);

    if (optionCount !== results.length) {
      setOptionCount(results.length);
    }

    return results;
  }, []);

  return (
    <>
      <Typography mb={2}>Option count: {optionCount}</Typography>
      <Autocomplete
        filterOptions={filterOptions}
        options={top100Films}
        sx={{ width: 300 }}
        renderInput={(params) => <TextField {...params} label="Movie" />}
      />
    </>
  );
}