Пользовательский интерфейс материала реагирует на автозаполнение, устанавливает другую метку и другое значение - PullRequest
0 голосов
/ 01 мая 2020

мы можем увидеть пример здесь на https://material-ui.com/components/autocomplete/

Я хотел установить метку опции и другое значение.

Как здесь, используется пример

    const defaultProps = {
       options: top5Films,
       getOptionLabel: (option) => option.title,
    };

    <Autocomplete
      {...defaultProps}
      id="auto-complete"
      value={value}
      onChange={(event, newValue) => {
        setValue(newValue);
      }}
      autoComplete
      includeInputInList
      renderInput={(params) => <TextField {...params} label="clearOnEscape" margin="normal"/>}
    />
    const top5Films= [
    { title: 'The Shawshank Redemption', year: 1994 },
    { title: 'The Godfather', year: 1972 },
    { title: 'The Godfather: Part II', year: 1974 },
    { title: 'The Dark Knight', year: 2008 },
    { title: '12 Angry Men', year: 1957 }
    ]

Но у меня есть данные вроде:

const top5Films= [
    { id: 1, title: 'The Shawshank Redemption', year: 1994 },
    { id: 2, title: 'The Godfather', year: 1972 },
    { id: 3, title: 'The Godfather: Part II', year: 1974 },
    { id: 4, title: 'The Dark Knight', year: 2008 },
    { id: 5, title: '12 Angry Men', year: 1957 }
    ]

Я хочу установить id в качестве значения и показать заголовок в качестве метки.

1 Ответ

1 голос
/ 01 мая 2020

Похоже, объекту присвоено значение.

Так что установка значения id для параметра привела к сбою параметров.

Я использовал идентификатор объекта следующим образом для дальнейшей работы.

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

export default function Playground() {
  const [value, setValue] = React.useState(null);
  const [id, setId] = React.useState(null);
  const [title, setTitle] = React.useState(null);

  return (
    <div>
      <div>{`value: ${value}`}</div>
      <div>{`id: ${id}`}</div>
      <div>{`title: ${title}`}</div>

      <br />
      <div style={{ width: 300 }}>
        <Autocomplete
          options={top5Films}
          getOptionLabel={option => option.title}
          id="movies"
          value={value}
          onChange={(event, newValue) => {
            console.log(newValue);
            if (newValue) {
              setValue(newValue);
              setId(newValue.id);
              setTitle(newValue.title);
            }
          }}
          renderInput={params => (
            <TextField {...params} label="Movies" margin="normal" />
          )}
        />
      </div>
    </div>
  );
}

// Top 5 films as rated by IMDb users. http://www.imdb.com/chart/top
const top5Films = [
  { id: 1, title: "The Shawshank Redemption", year: 1994 },
  { id: 2, title: "The Godfather", year: 1972 },
  { id: 3, title: "The Godfather: Part II", year: 1974 },
  { id: 4, title: "The Dark Knight", year: 2008 },
  { id: 5, title: "12 Angry Men", year: 1957 }
];

Пока это работает, но лучший ответ всегда приветствуется.

...