reactjs - 如何在 Typescript(输入组件)中使用 React Hook Form

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

该组件没有错误,但在我实际调用输入组件的索引文件中,它有一个错误,因为它不能使用 register = {register}。
有什么不见了?或者有什么问题?
https://codesandbox.io/s/react-hook-form-typescript-xnb1u

最佳答案

好这里的问题:

  • 您需要添加 register到输入组件 Prop 声明中的 Prop
  • 您必须使用 register作为 Prop 传递,而不是用 useForm 创建的新 Prop 在输入组件中
  • 输入元素缺少名称属性

  • 这里的工作<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;
    

    关于reactjs - 如何在 Typescript(输入组件)中使用 React Hook Form,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63381635/

    相关文章:

    javascript - 当输入改变时Jquery触发不起作用

    javascript - React Native 和 Firebase 实时数据库

    javascript - 不同参数的axios GET请求被丢弃

    javascript - 在页面入口处仅显示一次覆盖(不是路线更改)。如何?

    javascript - ReactJs + Babel - 使用单独的文件定义组件

    javascript - 如何在 javascript/typescript 中使用新的 Gremlin 3.x 语法编写旧查询

    node.js - 类型检查字符串而不是使用 instanceof

    php - 从表单将项目插入 MySQL 数据库

    javascript - Coldfusion 异步将表单发送到 cfc

    javascript - Typescript 泛型包装器 : Untyped function calls may not accept type arguments