材质UI可创建多选



我试图制作一个多选择组件,也可以使用材质UI创建,但我无法从文档中找出如何做到这一点。自动完成文档页

下面的例子是一个多选择组件,如果我单击键盘上的Enter键,它确实会添加新值,但它不会告诉用户他可以添加新值。然而,即使在这种情况下,我也不确定如何访问选定选项的新数组。

<Autocomplete
multiple
id="tags-filled"
options={top100Films.map(option => option.title)}
defaultValue={[top100Films[13].title]}
freeSolo
renderTags={(value, getTagProps) =>
value.map((option, index) => (
<Chip
variant="outlined"
label={option}
{...getTagProps({ index })}
/>
))
}
renderInput={params => (
<TextField
{...params}
variant="filled"
label="freeSolo"
placeholder="Favorites"
/>
)}
/>

我发现了另一个例子,建议使用filterOptions prop添加新值,但由于某种原因,它不能与前一个组件一起工作。

filterOptions={(options, params) => {
const filtered = filter(options, params);
// Suggest the creation of a new value
if (params.inputValue !== "") {
filtered.push({
inputValue: params.inputValue,
title: `Add "${params.inputValue}"`
});
}
return filtered;
}}

下面是我提到的例子的代码盒:codesandbox示例

所以我想要实现的是通过显示用户添加新值的选项来创建multiselect组件,并访问最终的选项数组。

非常感谢你的帮助。

虽然这可能无法解决您的确切需求-它确实允许您捕获值,并按回车键创建芯片,遵循gmail的电子邮件添加功能。

/* eslint-disable no-use-before-define */
import React from "react";
import Chip from "@material-ui/core/Chip";
import Autocomplete from "@material-ui/lab/Autocomplete";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
const useStyles = makeStyles((theme) => ({
root: {
width: 500,
"& > * + *": {
marginTop: theme.spacing(3)
}
}
}));
export default function Tags() {
const classes = useStyles();
const handleChange = (x, emails) => console.log(x, emails);
return (
<div className={classes.root}>
<Autocomplete
multiple
id="tags-filled"
onChange={handleChange}
options={[]}
defaultValue={""}
freeSolo
renderTags={(value, getTagProps) =>
value.map((option, index) => (
<Chip label={option} {...getTagProps({ index })} />
))
}
renderInput={(params) => (
<TextField
{...params}
variant="outlined"
label="Emails"
placeholder="Add Email"
/>
)}
/>
</div>
);
}

最新更新