iph*_*nic 2 javascript typescript reactjs material-ui react-hook-form
尝试使用用react-hook-form Controller包装的Material UI中的RadioGroup,总是得到所选值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>
)}
/>
);
}
Run Code Online (Sandbox Code Playgroud)
这是实时代码。
只需从列表中选择任何值,然后在控制台中按提交,您就会看到该值始终为空。
感谢帮助。
在你的身上RadioFieldElement.tsx,你不需要穿上{...register(name)}你的RadioGroup. 只需删除它,一切就会按预期工作:
<RadioGroup
{...field}
// remove this line ---> {...register(name)}
row
onChange={(event, value) => field.onChange(value)}
value={field.value}
>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3507 次 |
| 最近记录: |