我在我的应用程序中使用了 react-hook-form,我在 react-hook-form 中使用了自动完成。
我的自动完成有下拉值,如 1988、1987、1986,我认为我不需要为此自动完成使用 onchange 事件,当我从下拉列表中选择 1988 时,该值由 react-hook-form 传递而不使用 onchange 事件. , 但是,当我从自动完成中选择一个值并提交 react-hook-form 时,0 被作为参数传递而不是实际值。
我知道我们可以使用 onChange 事件并将选定的下拉值设置为状态,但是我不考虑对表单变量进行任何状态管理,因为 react-hook-form 内部使用状态管理并自动发送数据在提交表格时。 下面是我的代码。我可以知道使用 onChange 事件然后将选定的下拉值设置为 state 是否是唯一的解决方案?
export default function RegistratioinForm() {
const { handleSubmit, control } = useForm();
const handleSubmit = (data) => {
console.log(data) (here in this data, I am seeing 0 as being passed, instead of the selected values 1988 or 1987 or 1986
}
const options = [1988, 1987, 1986]
return(
<form className={classes.root} onSubmit={handleSubmit(onSubmit)}>
<Grid
<AutoComplete
options={options}
control={control}
name="year"
label="Select Year" (I am not using onchange event expecting that react-hook-form sends the selected dropdown value directed, however 0 is being passed when I select any one of the dropdown values.)
/>
);
答案 0 :(得分:1)
您需要使用 react-hook-form 中的 Controller
。
您使用的是什么自动完成组件?此示例假定您使用 @material-ui/lab
中的自动完成:
<Controller
name={"year"}
control={control}
render={({ field: { onChange, ...controllerProps } }) => (
<Autocomplete
{...controllerProps}
onChange={(e, data) => onChange(data)}
options={options}
getOptionLabel={(option) => option.title}
renderInput={(params) => <TextField {...params} label="Select Year" />}
)}
/>
)}
/>