【发布时间】:2021-04-23 17:33:16
【问题描述】:
目标
我有一个多重字段:
- 我们可以选择自动完成中存在的用户(我通过 API 检索的列表)
- 我们可以输入新用户的名字,并用逗号分隔
为此,我需要检索 value 和 inputValue 的值。对于value,没有问题,但是对于inputValue,有一些我不明白的地方
问题
当我在onInputChange中修改inputValue的值时,其状态被修改并重置like that
信息
我基于the example that material UI offers
代码
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) => users.includes(el.id))}有什么意义? -
检索选定用户的列表,因为值的类型是User
标签: javascript reactjs typescript material-ui