And*_*Ooi 2 reactjs material-ui
我正在尝试编写代码以在键盘输入时异步搜索多选组合。
然而我在最新版本(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>
);
}
Run Code Online (Sandbox Code Playgroud)
codeSandbox如下:https://codesandbox.io/s/controllablestates-material-demo-forked-ygqp2?file=/ demo.tsx
如果您在 codeSandbox 中尝试,您将无法在 TextField 字段中输入任何内容。
但是,如果您切换评论:
const [value, setValue] = React.useState<any | null>([]);
// const value = [];
Run Code Online (Sandbox Code Playgroud)
您将能够在文本字段字段中输入内容。这里到底发生了什么?值根本没有改变。
谁能弄清楚为什么我的第一个代码(其中值是 const 空数组)不起作用?
我问的原因是我需要将(受控)值作为 props 传递,然后将其设置为默认值 [] (如果它为 null)。我发现由于这种默认设置,我无法在文本字段中输入内容。
如果您正在使用react-hook-form您可以使用以下命令设置自动完成功能
multiple添加多个值,options:您添加要选择的选项getOptionLabel: 显示选项标签onChange:使用onChange函数react-hook-form设置选定的值renderInput:渲染输入import { useForm, Controller } from \'react-hook-form\'\nimport {\n Box,\n TextField,\n Autocomplete,\n} from \'@mui/material\'\n\nconst {\n ...\n control,\n formState: { errors },\n} = useForm()\n\n<Box mt={2}>\n <Controller\n control={control}\n name="industries"\n rules={{\n required: \'Veuillez choisir une r\xc3\xa9ponse\',\n }}\n render={({ field: { onChange } }) => (\n <Autocomplete\n defaultValue={\n useCasesData?.industries\n ? JSON.parse(useCasesData?.industries)\n : []\n }\n multiple\n disableCloseOnSelect\n options={companyIndustryTypes}\n getOptionLabel={(option) => option.name}\n onChange={(event, values) => {\n onChange(values)\n }}\n renderInput={(params) => (\n <TextField\n {...params}\n label="Type d\'industries"\n placeholder="Type d\'industries"\n helperText={errors.industries?.message}\n error={!!errors.industries}\n />\n )}\n />\n )}\n />\n</Box>\nRun Code Online (Sandbox Code Playgroud)\n\n\n请注意我的例子中的选项
\ncompanyIndustryTypes是一个对象数组:
[\n {\n id: 1,\n name: "Accounting",\n },\n {\n id: 2,\n name: "Administration & Office Support",\n },\n ...\n]\nRun Code Online (Sandbox Code Playgroud)\n\n
| 归档时间: |
|
| 查看次数: |
14829 次 |
| 最近记录: |