如何解决如何使用带有Typescript的React Hook表单输入组件
该组件没有错误,但是在我实际调用输入组件的索引文件中,它有一个错误,因为它不能使用register = {register}。
缺少什么?还是怎么了?
https://codesandbox.io/s/react-hook-form-typescript-xnb1u
解决方法
好的,这里有问题:
- 您需要在输入组件props声明中的props上添加
register
- 您必须使用作为道具传递的
register
,而不是在Input组件中使用useForm
创建的新道具 - 输入元素缺少名称属性
此处的工作<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;
,
我找到了一篇文章,帮助我找到了解决方法。
对于希望通过React Hook Form使用打字稿组件化的人来说,Codebox是正确的解决方案。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。