reactjs 如何获取和设置自动完成多个值?

qpgpyjmq  于 2023-04-20  发布在  React
关注(0)|答案(1)|浏览(103)

我在这个公会做了一个文本字段。但是我不能得到这个字段的值,有什么建议吗?
https://mui.com/material-ui/react-autocomplete/#multiple-values

const categories = [
   {id:1, name: "blog"},
   {id:2, name: "music"},
   {id:3, name: "video"},
]
 const [category, setCategory]: any = useState([]);

 <Autocomplete
                                            multiple
                                            limitTags={1}
                                            value={category}
                                            onChange={(event, newValue) => {
                                                setCategory([
                                                    ...category,
                                                    newValue
                                                ]);
                                            }}
                                            id="category-filter"
                                            options={categories}
                                            getOptionLabel={(option) => option.name}
                                            renderInput={(params) => (
                                                <TextField {...params} label="Category" placeholder="categories" />
                                            )}

                                        />
djp7away

djp7away1#

onChange处理程序中的newValue已经是一个选定选项的数组,因此您可以简单地将其设置到category中。
另外,由于每个选项都是一个对象,因此必须添加isOptionEqualToValue属性来告诉组件如何将选项与所选值进行比较。代码如下:

import { useState } from "react";
import { Autocomplete, TextField } from "@mui/material";

export const Test = () => {
  const categories = [
    { id: 1, name: "blog" },
    { id: 2, name: "music" },
    { id: 3, name: "video" }
  ];
  const [category, setCategory] = useState([]);
  return (
    <Autocomplete
      multiple
      limitTags={1}
      value={category}
      onChange={(event, newValue) => {
        setCategory(newValue);
      }}
      id="category-filter"
      options={categories}
      getOptionLabel={(option) => option.name}
      isOptionEqualToValue={(option, value) => option.id === value.id}
      renderInput={(params) => (
        <TextField {...params} label="Category" placeholder="categories" />
      )}
    />
  );
};

相关问题