【问题标题】:How to use Material-UI Autocomplete component to select multiple options and add new options?如何使用 Material-UI Autocomplete 组件选择多个选项并添加新选项?
【发布时间】:2021-04-23 17:33:16
【问题描述】:

目标

我有一个多重字段:

  1. 我们可以选择自动完成中存在的用户(我通过 API 检索的列表)
  2. 我们可以输入新用户的名字,并用逗号分隔

为此,我需要检索 valueinputValue 的值。对于value,没有问题,但是对于inputValue,有一些我不明白的地方

问题

当我在onInputChange中修改inputValue的值时,其状态被修改并重置like that

信息

我基于the example that material UI offers

Code in Sandbox

代码

import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";

interface User {
  id: number;
  name: string;
}

const userList: User[] = [
  { id: 1, name: "name 1" },
  { id: 2, name: "name 2" },
  { id: 3, name: "name 3" }
];

export default function AutocompleteControlled() {

  const [users, setUsers] = React.useState<number[]>([]);
  const [inputValue, setInputValue] = React.useState("");

  return (
    <div>
      <br />
      <Autocomplete
        multiple
        value={userList.filter((el) => users.includes(el.id))}
        onChange={(event: any, newValue: User[]) => {
          setUsers(newValue.map((el) => el.id));
        }}
        inputValue={inputValue}
        onInputChange={(event: any, newInputValue: string) => {
          console.log("newInputValue", newInputValue);
          setInputValue(newInputValue);
        }}
        id="controllable-states-demo"
        options={userList}
        getOptionLabel={(option) => option.name}
        renderInput={(params) => (
          <TextField {...params} label="Controllable" variant="outlined" />
        )}
      />
    </div>
  );
}

欢迎所有 cmets :)

【问题讨论】:

  • 这个value={userList.filter((el) =&gt; users.includes(el.id))}有什么意义?
  • 检索选定用户的列表,因为值的类型是User

标签: javascript reactjs typescript material-ui


【解决方案1】:

您希望启用多选,并允许用户在文本框中输入任意值。因此,您可以使用 Autocomplete 组件并将 freesolo 属性设置为 true,因此文本框可以包含任意值。

This 是最接近您的用例的 Material-UI 示例。

我们将使用受控组件,因此您可以使用 valueonChange 属性控制其行为。检查下面的代码。

您可以从预先填写的项目中进行选择,也可以输入任意值并按回车键,将在组件中添加一个芯片,并将该值添加到该状态的数组中。

目前value 是一个名称数组,但您可以将其设置为ids 或任何您想要的。

试试这个代码:

import React from "react";
import Chip from "@material-ui/core/Chip";
import Autocomplete from "@material-ui/lab/Autocomplete";
import { createStyles, makeStyles, Theme } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      width: 500,
      "& > * + *": {
        marginTop: theme.spacing(3),
      },
    },
  })
);

interface User {
  id: number;
  name: string;
}

const userList: User[] = [
  { id: 1, name: "name 1" },
  { id: 2, name: "name 2" },
  { id: 3, name: "name 3" },
  { id: 4, name: "name 4" },
  { id: 5, name: "name 5" },
];

export default function AutocompleteControlled() {
  const classes = useStyles();

  const [value, setValue] = React.useState<any>([userList[0].name]);

  console.log("value: ", value);

  return (
    <div className={classes.root}>
      <Autocomplete
        value={value}
        onChange={(event, newValue) => {
          setValue(newValue);
        }}
        multiple
        id="tags-filled"
        options={userList.map((option) => option.name)}
        freeSolo
        renderTags={(value: string[], getTagProps) =>
          value.map((option: string, index: number) => (
            <Chip
              variant="outlined"
              label={option}
              {...getTagProps({ index })}
            />
          ))
        }
        renderInput={(params) => (
          <TextField
            {...params}
            variant="filled"
            label="Users"
            placeholder="Search"
          />
        )}
      />
    </div>
  );
}

这就是它的样子,控制值被记录到控制台。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-18
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2014-07-28
    • 2021-12-20
    相关资源
    最近更新 更多