简体   繁体   English

如何使用 Material-UI 自动完成组件到 select 多个选项并添加新选项?

[英]How to use Material-UI Autocomplete component to select multiple options and add new options?

goal目标

I have a multiple field that:我有一个多个字段:

  1. we can select users present in the autocompletion (a list that I retrieve via API)我们可以 select 用户出现在自动完成中(我通过 API 检索的列表)
  2. We can enter the names of new users that we separate them with a comma我们可以输入用逗号分隔的新用户的名称

For that, I therefore need to retrieve the value of value and inputValue .为此,我因此需要检索valueinputValue的值。 For value , there is no problem but for inputValue , there is something that I do not understand对于value ,没有问题,但是对于inputValue ,有一些我不明白的地方

problem问题

When I modify the value of inputValue in onInputChange , its state is modified and reseted like that当我在onInputChange中修改inputValue的值时,它的 state 会像这样修改和重置

information信息

I base on the example that material UI offers我基于Material UI 提供的示例

Code in Sandbox 沙盒中的代码

Code代码

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>
  );
}

All comments are welcome:)欢迎大家发表意见:)

You want to enable multi selection, and allow the user to enter any arbitrary value in the textbox.您想启用多选,并允许用户在文本框中输入任意值。 Therefore you can use the Autocomplete component with the freesolo prop set to true, so the textbox can contain any arbitrary value.因此,您可以使用将freesolo设置为 true 的Autocomplete组件,因此文本框可以包含任意值。

This is the Material-UI example closest to your use case. 是最接近您的用例的 Material-UI 示例。

We will use a controlled component, so you can control its behavior with the value and onChange props.我们将使用受控组件,因此您可以使用valueonChange道具控制其行为。 Check the code below.检查下面的代码。

You can select from the pre-populated items, or you can enter any arbitrary value and press enter, and a chip will be added to the component, and the value will be added to the array in the state.您可以从预填充的项目中输入 select,也可以输入任意值并回车,一个芯片将添加到组件中,该值将添加到 state 中的数组中。

Currently value is an array of the names but you can set it to the id s or whatever you want.当前value是一个名称数组,但您可以将其设置为id或任何您想要的。

Try this code:试试这个代码:

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>
  );
}

This is how it looks, the controlled value is logged to the console.这就是它的外观,受控值记录到控制台。

截屏

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法 select Material UI 的自动完成组件中的选项 - Cannot select Options from Material UI's Autocomplete Component Material-UI 自动完成 - 单击图标时仅显示选项 - Material-UI autocomplete - Only show options when click icon React Material-UI 自动完成自定义“无选项”文本 - React Material-UI Autocomplete customize `no options` text 如何更改 Material ui 自动完成中选项的字体大小? - How to change fontsize of options in Material ui autocomplete? 如何通过innerHTML添加material-ui组件? - How to add material-ui component by innerHTML? Material-UI和Redux-form,re渲染选项点击选择,如何防止? - Material-UI and Redux-form, re renders options clicked on select, how to prevent it? 单击所选选项的特定区域时,如何防止打开 material-ui Select 选项 - How can I prevent material-ui Select options to be opened when clicking on particular area of the selected option 使用 material-ui 右对齐菜单选项 - Right align menu options with material-ui ui-选择如何从多选下拉菜单中的文本中添加新选项 - ui-select how to add new options from text in a multiple select dropdown 如何获取 material-ui 的自动完成 Select 的值? - How can I get the value of the Autocomplete Select of material-ui?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM