如何将 React Hook Form 与 Typescript(输入组件)一起使用

Cad*_*adu 5 forms typescript reactjs react-hooks react-hook-form

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

缺什么?或者出了什么问题?

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

Luc*_*lli 10

好的,问题在这里:

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

这是带有注释的工作<Input>组件:

import React, { InputHTMLAttributes } from "react";
import {
  FieldValues,
  UseFormRegister,
  // useForm, // don't need this import
} from "react-hook-form";

interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
  id: string;
  label: string;
  register: UseFormRegister<FieldValues>; // 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 />
      
      {/* react-hook-form v6 */}
      {/* you must declare the `name` attribute on the input element */}
      <input name={id} type="text" id={id} ref={register} {...rest} />

      {/* react-hook-form v7 */}
      {/* In v7 the register() function returns all the needed properties */}
      {/* see: https://dev.to/bluebill1049/what-s-coming-in-react-hook-form-version-7-4bfa */}
      {/* <input type="text" id={id} {...register(id)} {...rest} /> */}
    </div>
  );
};

export default Input;
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考,“register”属性实际上是“UseFormRegister&lt;FieldValues&gt;”类型。 (7认同)
  • `register: UseFormRegister&lt;FieldValues&gt;;` 这是预期的类型。您可以将它们导入为 `import { FieldValues, UseFormRegister } from "react-hook-form";` (2认同)
  • 我无法正常工作,我收到此错误“类型'FieldValues'缺少类型中的以下属性”,然后它列出了我的所有表单字段 (2认同)