我正在尝试编写代码以在键盘输入时异步搜索多选组合。
但是我在最新版本(5.2.2)中发现了一个我无法解释的奇怪行为。我提炼出以下问题(基于 MUI 自动完成页面的示例):
import * as React from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
const options = [
{ label: "Option 1", value: 1 },
{ label: "Option 2", value: 2 }
];
export default function ControllableStates() {
// const [value, setValue] = React.useState<any | null>([]);
const value = [];
const [inputValue, setInputValue] = React.useState("");
console.log("Current Value:", value);
return (
<div>
<div>{`value: ${value !== null ? `'${value}'` : "null"}`}</div>
<div>{`inputValue: '${inputValue}'`}</div>
<br />
<Autocomplete
multiple={true}
value={value}
onChange={(event: any, newValue: any | null) => {
//setValue(newValue);
}}
inputValue={inputValue}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
id="controllable-states-demo"
options={options}
sx={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Controllable" />}
/>
</div>
);
}
codeSandbox如下:https://codesandbox.io/s/controllablestates-material-demo-forked-ygqp2?file=/demo.tsx
如果您在 codeSandbox 中尝试,您将无法在 TextField 字段中输入任何内容。
但是,如果您切换评论:
const [value, setValue] = React.useState<any | null>([]);
// const value = [];
您将能够在 TextField 字段中输入内容。这里到底发生了什么?该值根本没有改变。
任何人都可以弄清楚为什么我的第一个代码(其中值是 const 空数组)不起作用?
我问的原因是我需要将(受控)值作为 props 传入,然后如果它为 null,则将其设置为默认值 []。我发现由于这种默认设置,我无法在 TextField 中输入内容。
最佳答案
如果您使用react-hook-form
,您可以使用设置自动完成
multiple
添加多个值,选项
:您添加要选择的选项getOptionLabel
:显示选项标签onChange
:使用react-hook-form
的onChange函数设置选定的值renderInput
:渲染输入
import { useForm, Controller } from 'react-hook-form'
import {
Box,
TextField,
Autocomplete,
} from '@mui/material'
const {
...
control,
formState: { errors },
} = useForm()
<Box mt={2}>
<Controller
control={control}
name="industries"
rules={{
required: 'Veuillez choisir une réponse',
}}
render={({ field: { onChange } }) => (
<Autocomplete
defaultValue={
useCasesData?.industries
? JSON.parse(useCasesData?.industries)
: []
}
multiple
disableCloseOnSelect
options={companyIndustryTypes}
getOptionLabel={(option) => option.name}
onChange={(event, values) => {
onChange(values)
}}
renderInput={(params) => (
<TextField
{...params}
label="Type d'industries"
placeholder="Type d'industries"
helperText={errors.industries?.message}
error={!!errors.industries}
/>
)}
/>
)}
/>
</Box>
Note that options in my case
companyIndustryTypes
is an array of object :
[
{
id: 1,
name: "Accounting",
},
{
id: 2,
name: "Administration & Office Support",
},
...
]
关于reactjs - MUI 自动完成(多个)控制值 - 神秘的输入行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70193775/