【问题标题】:What type is register from react-hook-form?react-hook-form 中的寄存器是什么类型?
【发布时间】:2022-01-23 06:23:41
【问题描述】:

在 Typescript 中使用 react-hook-form 时,有一个组件会发送一些 props,register 就是其中之一。

问题在于它在接口中声明时的类型:

export interface MyProps {
  title: string;
  ...
  register: (string | undefined) => void;
}

在这里声明register的正确方法是什么?

也尝试过:

import { RegisterOptions } from 'react-hook-form';
    export interface MyProps {
      title: string;
      ...
      register: RegisterOptions;
    }

【问题讨论】:

  • 您使用的是 react-hook-form 版本 6 还是 7?因为它从一个版本到另一个版本发生了很大变化。
  • 根据 package.json 是"react-hook-form": "^7.15.2",
  • 只需查看文档。类型在页面顶部react-hook-form.com/api/useform/register
  • @Khorne07 输入它作为答案.. 你可以获得积分

标签: javascript reactjs typescript typescript-typings react-hook-form


【解决方案1】:

试试这个。

import { RegisterOptions, UseFormRegisterReturn } from 'react-hook-form';

export interface MyProps {
  title: string;
  ...
  register: (name: string, options?: RegisterOptions) => UseFormRegisterReturn;
}

【讨论】:

    【解决方案2】:

    您可以从UseFormReturn 检索寄存器类型。

    import { UseFormReturn } from 'react-hook-form';
    
    export interface MyProps {
      title: string;
      register: UseFormReturn['register'];
    }
    

    在 react-hook-form 中,我们建议转发 ref 而不是传递register 方法。

    【讨论】:

      【解决方案3】:

      如果您将 register 作为自定义组件中的道具调用或在 Typescript 中的某些自定义输入字段中使用,则可以使用以下代码。

      首先从 'react-hook-form' 导入 UseFormRegister 和 FieldValues

      import {UseFormRegister, FieldValues } from 'react-hook-form'
      

      之后,定义寄存器的类型为

      register: UseFormRegister<FieldValues>
      

      并且繁荣,您不需要使用“任何”类型进行注册。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-20
        • 2017-06-15
        • 2021-11-15
        • 2012-06-15
        • 2021-06-17
        • 1970-01-01
        相关资源
        最近更新 更多