如何使用带有 Typescript 的 React Hook 表单(输入组件)

Posted

技术标签:

【中文标题】如何使用带有 Typescript 的 React Hook 表单(输入组件)【英文标题】:How to use React Hook Form with Typescript (Input Component) 【发布时间】:2020-12-02 12:05:46 【问题描述】:

组件没有错误,但在我实际调用输入组件的索引文件中,它有错误,因为它不能使用 register = register。

缺少什么?或者怎么了?

https://codesandbox.io/s/react-hook-form-typescript-xnb1u

【问题讨论】:

我找到了一篇帮助我找到解决方案的文章。 Codebox 为那些想要使用 React Hook Form 使用 typescript 组件化的人提供了正确的解决方案。 【参考方案1】:

我找到了一篇帮助我找到解决方案的文章。

Codebox 为那些想要使用 React Hook Form 使用 typescript 组件化的人提供了正确的解决方案。

https://codesandbox.io/s/react-hook-form-typescript-xnb1u

【讨论】:

【参考方案2】:

这里有问题:

    需要在Input组件props声明中的props中添加register 您必须使用作为道具传递的register,而不是在输入组件中使用useForm 创建的新道具 输入元素缺少名称属性

这里是带有 cmets 的工作 <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;

【讨论】:

感谢卢卡的帮助。 仅供参考,register 属性实际上是 UseFormRegister&lt;FieldValues&gt; 类型。

以上是关于如何使用带有 Typescript 的 React Hook 表单(输入组件)的主要内容,如果未能解决你的问题,请参考以下文章