[英]REACT-FORM-HOOK TypeError: Cannot read property 'type' of undefined
[英]Custom input from react-form-hook not working
按照此处的示例,我有一个自定义输入组件:
输入.tsx
import React from "react";
export default function Input({label, name, onChange, onBlur, ref}:any) {
return (
<>
<label htmlFor={name}>{label}</label>
<input
name={name}
placeholder="Jane"
onChange={onChange}
onBlur={onBlur}
ref={ref}
/>
</>
);
}
使用示例:
import {useAuth} from '../components/AuthContextProvider'
import { useForm, SubmitHandler } from "react-hook-form";
import Input from '../components/Input'
function Subscriptions({ Component, pageProps }: any) {
const { user } = useAuth()
const { register, handleSubmit, formState: { errors } } = useForm<Inputs>();
const onSubmit: SubmitHandler<Inputs> = async data => {
console.log(data, 'data sdfdsg')
}
return (
<>
<form onSubmit={handleSubmit(onSubmit)}>
<Input label="name" {...register('name')}/>
<button type='submit'>Add kid</button>
</form>
</>
)
}
export default Subscriptions
这是我的 package 版本:
"react-hook-form": "^7.34.2"
有什么想法我在这里做错了吗?
自定义输入接收未定义,但它适用于普通<input />
标签。
我在代码框中使用了该示例,它引发了有关ref
的错误,并建议使用React.forwardRef
,将您的自定义输入更改为:
function Input({ label, name, onChange, onBlur }, ref) {
return (
<>
<label htmlFor={name}>{label}</label>
<input
name={name}
placeholder="Jane"
onChange={onChange}
onBlur={onBlur}
ref={ref}
/>
</>
);
}
const MyInput = React.forwardRef(Input);
export default MyInput;
顺便说一句, ref
不是props
的一部分我不知道为什么这个例子有这样的,有必要使用forwardRef
所以它作为第二个参数传递。
你可以在这个代码框里看到完整的例子
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.