该组件没有错误,但在我实际调用输入组件的索引文件中,它有一个错误,因为它不能使用 register = {register}。
有什么不见了?或者有什么问题?
https://codesandbox.io/s/react-hook-form-typescript-xnb1u
最佳答案
好这里的问题:
register
到输入组件 Prop 声明中的 Prop register
作为 Prop 传递,而不是用 useForm
创建的新 Prop 在输入组件中 这里的工作
<Input>
带注释的组件:import React, { InputHTMLAttributes } from "react";
//import { useForm } from "react-hook-form"; // don't need the import
interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
id: string;
label: string;
register: any; // declare register props
}
const Input: React.FC<InputProps> = ({ id, label, register, ...rest }) => {
//const { register } = useForm(); // don't use a new `register`, use the one from props
return (
<div className="input-block">
<label htmlFor={id}>{label}</label>
<br />
<br />
{/* you must declare the `name` attribute on the input element */}
<input name={id} type="text" id={id} ref={register} {...rest} />
</div>
);
};
export default Input;
关于reactjs - 如何在 Typescript(输入组件)中使用 React Hook Form,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63381635/