![](/img/trans.png)
[英]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.