简体   繁体   中英

Perform autocomplete with two keys - Material UI with React

I'm trying to autocomplete the input when searched with either of the two values - title and year . However, it does only work when I search with title . When I search with year , it does not show any options.

Sample code

export default function ComboBox() {
  return (
    <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={(option) => option.title || option.year}
      style={{ width: 300 }}
      renderInput={(params) => (
        <TextField {...params} label="Combo box" variant="outlined" />
      )}
    />
  );
}

I have created a working example using Code Sandbox

Could anyone please help?

One way to make this work is to make the year part of the option label:

/* eslint-disable no-use-before-define */
import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";

import { top100Films } from "./movies";
export default function ComboBox() {
  return (
    <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={(option) => `${option.title} (${option.year})`}
      style={{ width: 300 }}
      renderInput={(params) => (
        <TextField {...params} label="Combo box" variant="outlined" />
      )}
    />
  );
}

编辑自动完成标题和年份

If you don't want to display the year, but still want to match on it, the other way is to use the filterOptions prop to customize the matching:

/* eslint-disable no-use-before-define */
import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import { createFilterOptions } from "@material-ui/lab/Autocomplete";
import { top100Films } from "./movies";

const filterOptions = createFilterOptions({
  stringify: (option) => `${option.title} ${option.year}`
});

export default function ComboBox() {
  return (
    <Autocomplete
      id="combo-box-demo"
      filterOptions={filterOptions}
      options={top100Films}
      getOptionLabel={(option) => option.title}
      style={{ width: 300 }}
      renderInput={(params) => (
        <TextField {...params} label="Combo box" variant="outlined" />
      )}
    />
  );
}

编辑自动完成标题和年份

Related documentation: https://material-ui.com/components/autocomplete/#custom-filter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM