如何在自动完成 Material-UI 中按 ID 或名称 select 选项

How to select option by id or by name in Autocomplete Material-UI

我无法找到解决方案,如何通过 idname 使用 Material-UI Autocomplete select 相同的选项].

我的选项数组:

const options = [
   {id: 1, name: 'onion'},
   {id: 2, name: 'potato'},
   {id: 3, name: 'carrot'}
]

我的期望:

这是我的代码的样子:

<Autocomplete
   classes={{
      root: classes.root
   }}
   style={{ padding: 0 }}
   options={options}
   getOptionLabel={(option) => option.name}
   renderInput={(params) => (
      <TextField
         {...params}
         required
         className='inputPadding'
         classes={{ root: classes.labelRoot }}
         label={t('mainRank')}
         variant='outlined'
         helperText={positionObjErr && t('required')}
         error={positionObjErr}
      />
   )}
   getOptionSelected={(opt, val) => opt === val}
   value={positionObj}
   onChange={(e, val) => {
      val && setPositionObj(val)
   }}
/>

您可以像下面这样为道具 getOptionSelected 设置一个条件,这样它会匹配字符串和 id


<Autocomplete
   classes={{
      root: classes.root
   }}
   style={{ padding: 0 }}
   options={options}
   getOptionLabel={(option) => option.name}
   renderInput={(params) => (
      <TextField
         {...params}
         required
         className='inputPadding'
         classes={{ root: classes.labelRoot }}
         label={t('mainRank')}
         variant='outlined'
         helperText={positionObjErr && t('required')}
         error={positionObjErr}
      />
   )}


   getOptionSelected={(opt, val) => opt.id === Number(val) || opt.name === val}


   value={positionObj}
   onChange={(e, val) => {
      val && setPositionObj(val)
   }}
/>

您可以覆盖默认 filterOptions 并使其在标签过滤器 returns 之后按 id 过滤 returns 无结果:

import TextField from "@material-ui/core/TextField";
import Autocomplete, {
  createFilterOptions
} from "@material-ui/lab/Autocomplete";

const options = [
  { id: 1, name: "onion" },
  { id: 2, name: "potato" },
  { id: 3, name: "carrot" }
];
const _filterOptions = createFilterOptions();
const filterOptions = (options, state) => {
  const result = _filterOptions(options, state);

  if (result.length === 0) {
    return _filterOptions(options, {
      ...state,
      getOptionLabel: (o) => o.id.toString()
    });
  }

  return result;
};

用法

export default function Filter() {
  return (
    <Autocomplete
      options={options}
      getOptionLabel={(option) => option.name}
      filterOptions={filterOptions}
      style={{ width: 300 }}
      renderInput={(params) => <TextField {...params} variant="outlined" />}
    />
  );
}

现场演示