Autocomplete Material UI 基于两个属性的搜索

Autocomplete Material UI search based on two attributes

我有这个数据:

const sample = [
    {hero: 'DARTH VADER', faction: 'EMPIRE'},
    {hero: 'LUKE SKYWALKER', faction: 'REBEL'},
    {hero: 'GREEDO', faction: 'BOUNTY HUNTER'},
];

使用自动完成,我可以通过 herofaction 属性搜索值,方法是在 [=13] 中分配其中之一=] 或 getOptionLabel={(option) => {option.faction}} prop.

但是我希望能够同时使用这两个属性进行搜索(键入 DARTH VADER 或 EMPIRE 将 return 得到相同的结果)。

题目如下:

  1. 我可以使用单个自动完成功能实现吗?
  2. 如果没有,我们可以使用切换来更改要在自动完成中查找的属性吗?

非常感谢

自动完成提供 filterOptions 属性。

您可以像这样使用它来提供自定义过滤器(这里是 codesandbox):

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

const filterOptions = createFilterOptions({
  matchFrom: 'any',
  stringify: (option) => option.hero + option.faction,
});

export default function Filter() {
  return (
    <Autocomplete
      id="filter-demo"
      options={sample}
      getOptionLabel={(option) => option.hero}
      filterOptions={filterOptions}
      renderInput={(params) => <TextField {...params} label="Custom filter" variant="outlined" />}
    />
  );
}

const sample = [
  {hero: 'DARTH VADER', faction: 'EMPIRE'},
  {hero: 'LUKE SKYWALKER', faction: 'REBEL'},
  {hero: 'GREEDO', faction: 'BOUNTY HUNTER'},
];