React Hook Form结合Material UI单选按钮初始值设置问题
React Hook Form + Material UI 单选按钮初始值同步问题解决方案
问题根源
直接用register绑定MUI RadioGroup时,组件初始选中状态无法自动同步到React Hook Form的表单值,核心原因是MUI组件内部状态与表单状态未通过正确方式绑定。
解决步骤
设置全局表单默认值
初始化useForm时指定对应字段的初始值,确保值的类型与Radio组件的value完全匹配:import { useForm, Controller } from "react-hook-form"; import { RadioGroup, FormControlLabel, Radio, Button } from "@mui/material"; export default function App() { const { control, handleSubmit, watch } = useForm({ defaultValues: { gender: "male" // 需与Radio的value属性值一致 } }); const onSubmit = (data) => console.log(data); console.log(watch("gender")); // 实时查看表单值变化 return ( <form onSubmit={handleSubmit(onSubmit)}> {/* 用Controller包裹RadioGroup实现状态同步 */} <Controller name="gender" control={control} render={({ field }) => ( <RadioGroup {...field} row> <FormControlLabel value="male" control={<Radio />} label="男" /> <FormControlLabel value="female" control={<Radio />} label="女" /> </RadioGroup> )} /> <Button type="submit" variant="contained">提交</Button> </form> ); }关键注意事项
- 必须使用
Controller包裹MUI RadioGroup,它会自动处理初始值注入、状态同步及事件绑定,替代手动设置value和onChange。 defaultValues中的字段名需与Controller的name严格一致,否则表单无法正确关联字段。- Radio组件的
value类型要与默认值完全匹配(比如默认值是字符串,Radio的value也必须是字符串,不能混用数字类型)。
- 必须使用
效果验证
初始化时watch("gender")会直接显示初始值male,提交表单时能正常获取该值,无需切换选项再切回即可同步。
内容的提问来源于stack exchange,提问作者Jean-François Handfield
相关产品推荐
相关产品推荐

