1

我正在 Typescript 中使用 react-hook-form 实现一个基本的用户注册表单。以下代码工作正常:

import React, { SyntheticEvent } from "react";
import { RouteComponentProps } from "@reach/router";
import { useForm } from "react-hook-form";

interface Props extends RouteComponentProps {
}

type Inputs = {
  user: {
    name: string;
    email: string;
  }
}

const SignupPage: React.FC<Props> = () => {
  const createUser = (data: Inputs) => console.log(data);

  const { errors, handleSubmit, register } = useForm();

  return(
    <form action="#" onSubmit={handleSubmit(createUser)}>
      <label htmlFor="user[email]">Email address</label>
      <input
        name="user[email]"
        placeholder="johndoe@example.com"
        type="text"
        ref={register({ required: true, pattern: /@/ })}
      />
      {errors.user?.email?.type === "required" && "Email can't be blank"}
      {errors.user?.email?.type === "pattern" && 'Email must include an "@"'}

      <label htmlFor="user[password]">Password</label>
      <input
        name="user[password]"
        placeholder="Minimum 6 characters"
        type="password"
        ref={register({ minLength: 6 })}
      />
      {errors.user?.password && 'Password must be at least 6 characters'}

      <input type="submit" />
    </form>
  );
};

export default SignupPage;

我遇到麻烦的地方是尝试将类型参数与useForm. 当我将相关行更改为:

  const { errors, handleSubmit, register } = useForm<Inputs, any>();

...编译失败Expected 0 type arguments, but got 2.

现在,react-hook-form 的 API 文档表明这是可行的,无论如何,文档可能是错误的,而且通常是错误的。但我也在查看源代码,react-hook-form v5.6.1,这是我确认我正在使用的,这就是源代码中的useForm定义:

export function useForm<
  FormValues extends FieldValues = FieldValues,
  ValidationContext extends object = object
>({ 
   // various parameters here 
})

所以我认为这些文档毕竟是对的,而我做错了什么。一点帮助?

4

0 回答 0