我有一个表单组件,它利用react-hook-form来处理表单提交。但是,我的MUI Radio组没有按照预期正确设置值。我有两个单选选项,男性和女性。目前,只有“男性”按钮有效。但是,如果我将“女性”放在第一位,那么“女性”按钮就会起作用。
这是我的组件:
<form onSubmit={handleSubmit(onSubmit)} style={{ display: 'flex', flexDirection: 'column', gap: '16px', maxWidth: '400px', margin: 'auto' }}>
<TextField
{...register('name', { required: true, minLength: 6, maxLength: 10 })}
label="Name"
variant="outlined"
fullWidth
/>
<TextField
{...register('email_address', { required: true })}
label="Email Address"
variant="outlined"
fullWidth
/>
<TextField
{...register('phone_number', { required: true })}
label="Phone Number"
variant="outlined"
fullWidth
/>
<FormControl component="fieldset" required>
<FormLabel>Gender</FormLabel>
<RadioGroup {...register('gender', { required: true })}>
<FormControlLabel value="Male" control={<Radio />} label="Male" />
<FormControlLabel value="Female" control={<Radio />} label="Female" />
</RadioGroup>
</FormControl>
<FormControl fullWidth variant="outlined">
<InputLabel id="cafe-select-label">Select Cafe</InputLabel>
<Select
labelId="cafe-select-label"
{...register('cafe_name')}
defaultValue=""
>
<MenuItem value="" disabled />
{cafes.map(cafe => (
<MenuItem key={cafe.name} value={cafe.name}>{cafe.name}</MenuItem>
))}
</Select>
</FormControl>
<Button type="submit" variant="contained" color="primary" fullWidth>
Submit
</Button>
</form>
我尝试记录表单的数据以查看发生了什么,当我选择顶部按钮时,值会按预期设置。当我选择第二个按钮时,该值会设置为 null。
您好,您可以使用
watch
中的react-hook-form
来检查单选按钮的值
const { register, handleSubmit, watch } = useForm();
const selectedGender = watch('gender', '');
<FormControl component="fieldset" required>
<FormLabel>Gender</FormLabel>
<RadioGroup {...register('gender', { required: true })}
value={selectedGender}>
<FormControlLabel value="Male" control={<Radio />} label="Male" />
<FormControlLabel value="Female" control={<Radio />} label="Female" />
</RadioGroup>
</FormControl>