javascript - react-hook-form 与 Material UI RadioGroup 选中的值总是 NULL
尝试使用 Material UI 的 RadioGroup 并用 react-hook-form 的 Controller 包裹,但总是得到选中的值为 null,这是我的代码,我想知道我遗漏了什么?
import * as React from "react";
import {
FormControl,
FormControlLabel,
FormHelperText,
Radio,
RadioGroup
} from "@mui/material";
import { useState } from "react";
import { useFormContext, Controller } from "react-hook-form";
interface IOptionTypes {
id: string;
label: string;
value: string;
desc?: string;
}
interface IFormElementTypes {
name: string;
options: IOptionTypes[];
}
export default function RadioFieldElement({
name,
options
}: IFormElementTypes) {
const {
control,
register,
formState: { errors }
} = useFormContext();
return (
<Controller
name={name}
defaultValue=""
control={control}
render={({ field }) => (
<FormControl fullWidth>
<RadioGroup
{...field}
{...register(name)}
row
onChange={(event, value) => field.onChange(value)}
value={field.value}
>
{options.map((option) => (
<FormControlLabel
key={option.id}
value={option.value}
control={<Radio />}
label={option.label}
/>
))}
</RadioGroup>
<FormHelperText>{String(errors[name]?.message ?? "")}</FormHelperText>
</FormControl>
)}
/>
);
}
这是实时代码。
只需从列表中选择任何值并在控制台中按提交,你会看到该值总是为 null。
谢谢你的帮助。
答案#1
在你的 RadioFieldElement.tsx 中,你不需要在 RadioGroup 上放置 {...register(name)}。只需删除它,一切就会按预期工作:
<RadioGroup
{...field}
// remove this line ---> {...register(name)}
row
onChange={(event, value) => field.onChange(value)}
value={field.value}
>
这里是一个完整的 codesandbox 示例:
答案#2
RadioFieldElement.tsx
import * as React from "react";
import {
FormControl,
FormControlLabel,
FormHelperText,
Radio,
RadioGroup
} from "@mui/material";
import { useState } from "react";
import { useForm, Controller } from "react-hook-form"; // use useForm
interface IOptionTypes {
id: string;
label: string;
value: string;
desc?: string;
}
interface IFormElementTypes {
name: string;
options: IOptionTypes[];
}
export default function RadioFieldElement({
name,
options
}: IFormElementTypes) {
const {
control,
register,
formState: { errors }
} = useForm();
/* const [theValue, setTheValue] = useState(control._defaultValues[name]);
const handleChange = (event) => {
console.log(event.target.value);
setTheValue(event.target.value);
}; */
return (
<Controller
name={name}
defaultValue=""
control={control}
render={({ field }) => (
<FormControl fullWidth>
<RadioGroup
{...field}
{...register(name)}
row
onChange={(event, value) => field.onChange(value)}
value={field.value}
>
{options.map((option) => (
<FormControlLabel
key={option.id}
value={option.value}
control={<Radio />}
label={option.label}
/>
))}
</RadioGroup>
<FormHelperText>{String(errors[name]?.message ?? "")}</FormHelperText>
</FormControl>
)}
/>
);
}