reactjs “react-hook-form”表单类型

1bqhqjot  于 2022-11-04  发布在  React
关注(0)|答案(1)|浏览(273)

我使用react hooks表单创建了这个表单:

import React from "react";
import ReactDOM from "react-dom";
import { useForm, SubmitHandler } from "react-hook-form";

import "./styles.css";

function App() {
  type FormValues = {
    firstName: string;
    lastName: string;
    email: string;
  };

  const { register, handleSubmit } = useForm<FormValues>();
  const onSubmit: SubmitHandler<FormValues> = (data) =>
    alert(JSON.stringify(data));

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <label>First Name</label>
        <input {...register("firstName")} />
      </div>

      <div>
        <label>Last Name</label>
        <input {...register("lastName")} />
      </div>

      <div>
        <label htmlFor="email">Email</label>
        <input type="email" {...register("email")} />
      </div>

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

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

现在,typescript强制我只使用FormValues中的键来注册输入的名称({...register("name")})。如果我将email: string;FormValues中删除,那么我将在<input type="email" {...register("email")} />上得到TS错误,并显示下一条消息:

Argument of type '"email"' is not assignable to parameter of type '"firstName" | "lastName"'.ts(2345)

问:如何解决这个问题,并使输入名称独立于FormValues
演示:https://codesandbox.io/s/react-hook-form-get-started-ts-forked-wfzjyr?file=/src/index.tsx:735-780

j8ag8udp

j8ag8udp1#

我看到的唯一解决办法是:

function App() {
  type FormValues = {
    firstName: string;
    lastName: string;
    // email: string;
  };

  const { register, handleSubmit } = useForm<FormValues>();
  const onSubmit: SubmitHandler<FormValues> = (data) =>
    alert(JSON.stringify(data));

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <label>First Name</label>
        <input {...register("firstName")} />
      </div>

      <div>
        <label>Last Name</label>
        <input {...register("lastName")} />
      </div>

      <div>
        <label htmlFor="email">Email</label>
        <input type="email" {...(register as UseFormRegister<any>)("email")} />
      </div>

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

基本上,您必须将寄存器键入为any,才不会触发typescript错误<input type="email" {...(register as UseFormRegister<any>)("email")} />
我能问一下你到底想达到什么目的吗,因为你在这里问的问题违背了打字稿和React钩形原则。
为什么您希望表单中的某个字段已注册,但未被typescript视为字段之一?可能有一个更好的解决方案可以解决您的问题。

相关问题