您可以使用以下方法回退到可控组件Controller https://react-hook-form.com/api/usecontroller/controller如果它不起作用。
就你的情况而言,我怀疑这是因为name
道具传递给你的RadioGroup
不一样 https://github.com/mui-org/material-ui/blob/ebeb1492b5e645eccdea920fbbf561fe2a0c3031/packages/material-ui/src/RadioGroup/RadioGroup.js#L56-L59 as the name
传递到本机输入时的属性,例如input
or select
.
react-hook-form
V7
const { handleSubmit, control } = useForm({
defaultValues: {
promoting2: '',
},
});
<FormControl component="fieldset">
<FormLabel component="legend">Promoting</FormLabel>
<Controller
rules={{ required: true }}
control={control}
name="promoting2"
render={({ field }) => (
<RadioGroup {...field}>
<FormControlLabel
value="business"
control={<Radio />}
label="Business"
/>
<FormControlLabel
value="nonprofit"
control={<Radio />}
label="Non-Profit"
/>
<FormControlLabel
value="event"
control={<Radio />}
label="Event"
/>
</RadioGroup>
)}
/>
</FormControl>
react-hook-form
V6
const { register, handleSubmit, errors, control } = useForm({
promoting: '',
});
const onSubmit = (data) => alert(JSON.stringify(data, null, 2));
<form onSubmit={handleSubmit(onSubmit)}>
<FormControl component="fieldset">
<FormLabel component="legend">Promoting</FormLabel>
<Controller
rules={{ required: true }}
control={control}
name="promoting"
as={
<RadioGroup>
<FormControlLabel
value="business"
control={<Radio />}
label="Business"
/>
<FormControlLabel
value="nonprofit"
control={<Radio />}
label="Non-Profit"
/>
<FormControlLabel
value="event"
control={<Radio />}
label="Event"
/>
</RadioGroup>
}
/>
</FormControl>
<input type="submit" />
</form>
如果你想读取值onChange
火灾,当将元素传递给as
props:
<Controller
{...}
as={
<MyComponent
onChange={handleChange} // handleChange will never be called
/>
}
/>
原因是因为Controller
将复制您传入的元素并传递它自己的元素onChange
将覆盖你的道具。看here https://github.com/react-hook-form/react-hook-form/blob/c18ceee1975651c14e1d33fc420f5eece0824f1f/src/controller.tsx#L14-L19 and here https://github.com/react-hook-form/react-hook-form/blob/c18ceee1975651c14e1d33fc420f5eece0824f1f/src/useController.ts#L201.
要解决这个问题,您需要使用另一种方法来传递元素render
props 来更好地控制如何渲染组件。
<Controller
rules={{ required: true }}
control={control}
name="promoting2"
render={({ name, onBlur, onChange, value }) => (
<RadioGroup
value={value}
onBlur={onBlur}
onChange={(e) => {
onChange(e);
console.log(e.target.value); // will be called this time
}}
>
<FormControlLabel
value="business"
control={<Radio />}
label="Business"
/>
{...}
</RadioGroup>
)}
/>