React Hook Form结合MUI RadioGroup值设置异常问题求助
解决React Hook Form结合MUI RadioGroup值无法正确设置的问题
问题根源
直接给MUI的RadioGroup传递register('gender')是错误用法。React Hook Form的register是为原生HTML输入元素设计的,而MUIRadioGroup的onChange回调参数是(event, value),和React Hook Form期望的参数格式不匹配,导致只有第一个单选选项能正常赋值,选第二个时值会变成null。
解决方案一:使用Controller组件(推荐)
用React Hook Form提供的Controller组件包裹MUIRadioGroup,它能自动处理自定义组件的表单值同步:
首先确保从react-hook-form导入Controller,然后修改性别选择区域的代码:
import { useForm, Controller } from "react-hook-form"; // ... 其他组件逻辑 <FormControl component="fieldset" required> <FormLabel>Gender</FormLabel> <Controller name="gender" control={control} // control来自useForm的返回值 rules={{ required: true }} render={({ field }) => ( <RadioGroup {...field}> <FormControlLabel value="Male" control={<Radio />} label="Male" /> <FormControlLabel value="Female" control={<Radio />} label="Female" /> </RadioGroup> )} /> </FormControl>
解决方案二:手动绑定值与 onChange
如果不想用Controller,可以手动通过watch获取当前值,用setValue更新表单数据:
import { useForm } from "react-hook-form"; const { register, handleSubmit, watch, setValue } = useForm(); const genderValue = watch('gender'); // ... 其他组件逻辑 <FormControl component="fieldset" required> <FormLabel>Gender</FormLabel> <RadioGroup value={genderValue} onChange={(e, value) => setValue('gender', value)} > <FormControlLabel value="Male" control={<Radio />} label="Male" /> <FormControlLabel value="Female" control={<Radio />} label="Female" /> </RadioGroup> </FormControl>
两种方式都能解决问题,优先推荐第一种Controller方案,它更贴合React Hook Form的设计规范,也能更顺畅地处理表单验证等逻辑。
内容的提问来源于stack exchange,提问作者daronoh
相关产品推荐
相关产品推荐

