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

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

缺少什么?或者怎么了?

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

【问题讨论】:

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

标签: reactjs typescript forms react-hooks react-hook-form


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    这里有问题:

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

    这里是带有 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; 类型。
    猜你喜欢
    • 2022-10-16
    • 1970-01-01
    • 2020-01-15
    • 2022-08-18
    • 2022-11-17
    • 1970-01-01
    • 2021-03-22
    • 2019-11-29
    • 2022-07-30
    相关资源
    最近更新 更多