如何在 react-hook-from 中使用 material-ui 自动完成功能
how to use material-ui autocomplete feature in react-hook-from
我在我的应用程序中使用了 react-hook-form,并且我在 react-hook-form 中使用了自动完成。
我的自动完成具有下拉值,如 1988、1987、1986,我认为我不需要为此自动完成使用 onchange 事件,当我从下拉列表中 select 1988 时,该值由 react-hook 传递-form 不使用 onchange 事件。
,
但是,当我 select 来自自动完成的值并提交 react-hook-form 时,0 被作为参数而不是实际值传递。
我知道我们可以使用 onChange 事件并将 selected 下拉值设置为状态,但是我不考虑对表单变量进行任何状态管理,因为 react-hook-form 内部使用状态管理并在提交表单时自动发送数据。
下面是我的代码。我可以知道是否使用 onChange 事件然后将 selected 下拉值设置为 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.)
/>
);
您需要使用来自 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" />}
)}
/>
)}
/>
我在我的应用程序中使用了 react-hook-form,并且我在 react-hook-form 中使用了自动完成。
我的自动完成具有下拉值,如 1988、1987、1986,我认为我不需要为此自动完成使用 onchange 事件,当我从下拉列表中 select 1988 时,该值由 react-hook 传递-form 不使用 onchange 事件。 , 但是,当我 select 来自自动完成的值并提交 react-hook-form 时,0 被作为参数而不是实际值传递。
我知道我们可以使用 onChange 事件并将 selected 下拉值设置为状态,但是我不考虑对表单变量进行任何状态管理,因为 react-hook-form 内部使用状态管理并在提交表单时自动发送数据。 下面是我的代码。我可以知道是否使用 onChange 事件然后将 selected 下拉值设置为 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.)
/>
);
您需要使用来自 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" />}
)}
/>
)}
/>