我正在尝试使用 UI 材质Select
里面有多个选项react-hook-form
没有成功。
在尝试使用多种选项之前我已经完成了这项工作
<form onSubmit={handleSubmit(onSubmit)}>
<Row className="mb-2">
<Col sm={6}>
<FormControl className="select-language">
<InputLabel> {t('Languages')}</InputLabel>
<Controller
as={
<Select>
{Config.languages.map(m => <MenuItem key={m.code} value={m.text}> {t(m.text)} </MenuItem>)}
</Select>
}
defaultValue={user.language}
name="language"
control={control}
>
</Controller>
</FormControl>
</Col>
</Row>
</form>
我尝试添加multiple
到 Select 元素,这导致我遇到另一个错误。
我也尝试只保留Select
元素没有Controller
包装器,但我无法获取语言值onSubmit
非常简单的 codeSandBox 显示我无法从中获取价值Select
提交表格时:https://codesandbox.io/s/react-hook-form-example-s7h5p?file=/src/index.js https://codesandbox.io/s/react-hook-form-example-s7h5p?file=/src/index.js
我将不胜感激任何帮助
谢谢
如果有人正在寻找简单的解决方案,这可能会派上用场。现在,使用“选择组件”,多个选择选项变得非常容易。如果您查看 Select 组件,您只需将默认值设置为数组并传递“multiple”属性即可。
import {
Button,
FormControl,
InputLabel,
MenuItem,
Select
} from "@mui/material";
import { Controller, useForm } from "react-hook-form";
const FCWidth = {
width: "20rem"
};
export default function App() {
const { control, handleSubmit } = useForm();
const formSubmitHandler = (formData) => {
console.log(formData);
};
const ages = ["10", "20", "30"];
return (
<div className="App">
<form onSubmit={handleSubmit(formSubmitHandler)}>
<Controller
name="age"
control={control}
type="text"
defaultValue={[]}
render={({ field }) => (
<FormControl sx={FCWidth}>
<InputLabel id="age">Age</InputLabel>
<Select
{...field}
labelId="age"
label="age"
multiple
defaultValue={[]}
>
{ages.map((age) => (
<MenuItem value={age} key={age}>
{age}
</MenuItem>
))}
</Select>
</FormControl>
)}
/>
<FormControl sx={FCWidth}>
<Button
type="submit"
variant="contained"
fullWidth
sx={{ marginTop: ".75rem", fontWeight: "bold" }}
>
Submit
</Button>
</FormControl>
</form>
</div>
);
}
这是代码沙箱链接https://codesandbox.io/s/select-multiple-option-with-mui-and-react-hook-form-2kv2o https://codesandbox.io/s/select-multiple-option-with-mui-and-react-hook-form-2kv2o
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)