下面是我推荐的方法。
该方法有两个主要方面:
使用“受控”输入方法,Autocomplete
以便您可以完全控制当前值。
使用适当的逻辑为输入指定onKeyDown
处理程序以添加新值。TextField
params.inputProps.onKeyDown
import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
export default function Tags() {
const [value, setValue] = React.useState([top100Films[13]]);
const handleKeyDown = event => {
switch (event.key) {
case ",":
case " ": {
event.preventDefault();
event.stopPropagation();
if (event.target.value.length > 0) {
setValue([...value, event.target.value]);
}
break;
}
default:
}
};
return (
<div style={{ width: 500 }}>
<Autocomplete
multiple
freeSolo
id="tags-outlined"
options={top100Films}
getOptionLabel={option => option.title || option}
value={value}
onChange={(event, newValue) => setValue(newValue)}
filterSelectedOptions
renderInput={params => {
params.inputProps.onKeyDown = handleKeyDown;
return (
<TextField
{...params}
variant="outlined"
label="filterSelectedOptions"
placeholder="Favorites"
margin="normal"
fullWidth
/>
);
}}
/>
</div>
);
}
// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
{ title: "The Shawshank Redemption", year: 1994 },
{ title: "The Godfather", year: 1972 },
// ... many more options
];
这是一个typescript版本:
/* eslint-disable no-use-before-define */
import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete, { RenderInputParams } from "@material-ui/lab/Autocomplete";
interface ObjectOption {
title: string;
year: number;
}
type Option = ObjectOption | string;
interface MyInputProps {
onKeyDown: (event: object) => void;
}
interface MyParams extends RenderInputParams {
inputProps: MyInputProps;
}
export default function Tags() {
const [value, setValue] = React.useState([top100Films[13]]);
const handleKeyDown = event => {
switch (event.key) {
case ",":
case " ": {
event.preventDefault();
event.stopPropagation();
if (event.target.value.length > 0) {
setValue([...value, event.target.value]);
}
break;
}
default:
}
};
return (
<div style={{ width: 500 }}>
<Autocomplete
multiple
freeSolo
id="tags-outlined"
options={top100Films}
getOptionLabel={option => {
if (typeof option === "string") {
return option;
}
return option.title;
}}
value={value}
onChange={(event, newValue) => setValue(newValue)}
filterSelectedOptions
renderInput={(params: MyParams) => {
params.inputProps.onKeyDown = handleKeyDown;
return (
<TextField
{...params}
variant="outlined"
label="filterSelectedOptions"
placeholder="Favorites"
margin="normal"
fullWidth
/>
);
}}
/>
</div>
);
}
// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films: ObjectOption[] = [
{ title: "The Shawshank Redemption", year: 1994 },
{ title: "The Godfather", year: 1972 },
// ... many more options
];