TypeError:注册不是在React中使用React Hook Form的函数

2024-03-28

The Error Message: Error Message: If i dont use the Inputs inside div then it works perfectly but when i use Input inside div it shows me this error.
I wanted to keep the hook related stuff separated so it look clean.
why does it only works when its not inside a div?

登录.tsx

import { useHistory } from "react-router-dom";
import { useForm } from "react-hook-form";

import useAuth from "./../hooks/useAuth";
import { Form, Input } from "../components/FormGroup";
import MacNav from "../components/MacNav";

import { loginActionUrl } from "./../services/ApiLinks";
import {
  fetchPostResopnse,
  successPopUp,
  errorPopUp,
} from "./../services/FormHelper";

type Tinputs = {
  username: string;
  password: string;
};

function Login() {
  const auth = useAuth();
  const history = useHistory();
  const methods = useForm<Tinputs>();

  const onSubmit = async (data: Tinputs) => {
    const result = await fetchPostResopnse(loginActionUrl, data);

    if (result.isAuth) {
      successPopUp("Credentials Matched", () => {
        auth.signIn(result);
        history.push("/admin/dashboard");
      });
    } else {
      errorPopUp("Credentials Does Not Matched");
    }
  };

  return (
    <div>
      <MacNav />

      <div className="section-secondary">
        <div className="container">
          <div className="contact-form-wrapper">
            <div className="title-lg text-center">Enter Your Credentials</div>
            <Form formMethods={methods} handler={onSubmit} submitBtn="Submit">
             {/*If i dont use Input inside div it works*/}
              <div>
                <Input name="username" rule={{ required: true }} />
              </div>
              <Input name="password" rule={{ required: true }} />
            </Form>
          </div>
        </div>
      </div>
    </div>
  );
}

export default Login;

我在这里编写了表单组件。 表单组.tsx

import React from "react";

const Form = ({ children, formMethods, handler, submitBtn }: any) => {
  return (
    <form onSubmit={formMethods.handleSubmit(handler)}>
      {React.Children.map(children, (child) => {
        return child.props.name ? (
          <div>
            {React.createElement(child.type, {
              ...{
                ...child.props,
                register: formMethods.register,
                key: child.props.name,
              },
            })}
            {child.props?.rule && formMethods.errors[child.props.name] && (
              <div className="text-danger">
                *
                {formMethods.errors[child.props.name].message
                  ? formMethods.errors[child.props.name].message
                  : `${child.props.name} is required`}
              </div>
            )}
          </div>
        ) : (
          child
        );
      })}
      {submitBtn && <button type="submit">{submitBtn}</button>}
    </form>
  );
};

const Input = ({ register, name, label, rule, ...rest }: any) => {
  label = label ? label : name?.charAt(0).toUpperCase() + name?.slice(1);
  return (
    <div>
      <label htmlFor={name}>{label}</label>
      <input name={name} ref={register(rule)} {...rest} />
    </div>
  );
};

const Textarea = ({ register, name, label, rule, ...rest }: any) => {
  label = label ? label : name?.charAt(0).toUpperCase() + name?.slice(1);
  return (
    <div>
      <label htmlFor={name}>{label}</label>
      <textarea name={name} ref={register(rule)} {...rest}></textarea>
    </div>
  );
};

const SubmitButton = ({ name, ...rest }: any) => {
  return (
    <button type="submit" {...rest}>
      {name}
    </button>
  );
};

export { Form, Input, Textarea, SubmitButton };


  [1]: https://i.stack.imgur.com/PvEUA.png

你好,根据你的代码,发生了什么,这是预期的

div 没有名称,因此根据此代码

{React.Children.map(children, (child) => {
        return child.props.name ? (
          <div>
            {React.createElement(child.type, {
              ...{
                ...child.props,
                register: formMethods.register,
                key: child.props.name,
              },
            })}
            {child.props?.rule && formMethods.errors[child.props.name] && (
              <div className="text-danger">
                *
                {formMethods.errors[child.props.name].message
                  ? formMethods.errors[child.props.name].message
                  : `${child.props.name} is required`}
              </div>
            )}
          </div>
        ) : (
          child
        );
      })}

还有下面这个孩子

<div>
  <Input name="username" rule={{ required: true }} />
/div>

输入组件将在没有 register 属性的情况下进行渲染,因此当它尝试在此处调用它时,但它的值未定义,会导致错误

ref={register(rule)}

我建议创建一个新组件

const InputWithDiv = (props) => (
<div>
  <Input rule={{ required: true }}  {..props} />
/div>
);

并像下面一样使用它

<Form formMethods={methods} handler={onSubmit} submitBtn="Submit">
  <InputWithDiv name="username" />
  <Input name="password" rule={{ required: true }} />
</Form>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TypeError:注册不是在React中使用React Hook Form的函数 的相关文章

随机推荐

  • 混合模式内容 - 如何从 h1 中选择文本但不包含其子元素的文本?

    我在打印简单文本时遇到问题 h1 元素 require nokogiri doc Nokogiri HTML h1 em Name em A Johnson h1 puts doc at xpath h1 content 它输出 NameA
  • 什么是 dict_keys、dict_items 和 dict_values?

    我在使用的时候遇到过这三种类型collections Counter的 viewkeys viewitems 和 viewvalues 方法 这三个方法返回的值都是类型dict keys dict items and dict values
  • 如何将TextView旋转90度并显示[重复]

    这个问题在这里已经有答案了 我在图表页面遇到一种情况LinearLayout应该显示TextView旋转 90 度 尝试这个
  • 在java中使用接口的实现类型

    我想创建一个接口 强制实现它的每个类对于实现的类的类型具有特定的功能 假设我有类 MyClassA MyClassB MyClassC 等 它们都需要自己类型的函数 在我的A班 public class MyClassA implement
  • TFS 2012 中的 SVN 标记等效项

    我最近迁移到TFS 2012我曾与SVN许久 在 SVN 中我使用了 Tags 标记一些重要的 检查站 开发 即当我完成一个软件版本 alpha beta 时 我创建了一个Tag对于那个版本 如果发生任何错误 我会 受保护的 现在 我需要在
  • knitr 如何将警告信息保留在盒子内?

    我正在使用 knit 编写教程 我想展示学生可能遇到的一些警告和错误 虽然我能够使用以下命令很好地显示框中的代码块tidy TRUE选项 我不明白如何处理警告和错误的显示 例如 如果我有以下代码 documentclass article
  • 如何将某个 S3 文件标记为公开

    如何通过 Web 服务 API 将某个 S3 文件标记为公开 使用方法setCannedAcl CannedAccessControlList PublicRead 更改访问控制权限 阅读 java 文档以获取详细信息here http d
  • 如何在R中拆分列?

    我也想以同样的方式拆分同一列 我想按如下方式执行此操作 但它无法正常工作 我使用的代码是t38kbat read table test38kbat txt header FALSE head t38kbat t38kbat lt separ
  • 如何在IE9中启用使用ajax加载本地文件

    我知道存在起源问题 但设置网络服务器不是这里的一个选项 Firefox v14 加载本地文件没有问题 添加 allow file access from files 后Chrome没有问题 有什么办法也修复IE9吗 谢谢 编辑 我找到了解决
  • Android SuperUser 应用程序如何检测应用程序请求 root?

    我正在编写一个将使用的应用程序su执行linux内核中的一些命令 我想知道超级用户如何确定应用程序正在请求 root 权限 另外 是否有任何已知的方法 通过混淆 可以绕过此检查 换句话说 尽管 Android 清单文件中没有明确请求权限 A
  • Mysqli 查询返回空结果

    我试图使用以下代码从我的数据库获取一些数据
  • Jetpack 撰写预览因 hiltViewModel<>() 崩溃

    我使用 compose 版本 1 1 0 beta03 和 hilt navigation compose 1 0 0 beta01 这是我的可组合代码 fun EngagementBotChart modifier Modifier Mo
  • 两条线相交的算法?

    我有2行 两条线都包含 X 和 Y 两个点 这意味着它们都有长度 我看到两个公式 一个使用行列式 一个使用普通代数 哪个计算效率最高 公式是什么样的 我很难在代码中使用矩阵 这就是我目前所拥有的 它可以更有效吗 public static
  • spring-cloud-starter-config POST /env 不起作用

    我有一个小的 Spring Boot Web 应用程序 可执行 jar 它在 application properties 文件中有一些自定义属性 我的目标是能够在运行时动态更改这些属性 而无需运行构建 部署或重新启动 java 进程 sp
  • 从 kdb 中的字符串中提取数字

    我对 kdb q 很陌生 我遇到过从字符串中提取数字的问题 有什么建议么 Example AZXER 1234 MARKET should output 1234 Assume that there is only one number i
  • JOIN 语法中缺少关键字

    在提出问题之前我已经搜索过该网站 但没有遇到相关的内容 我确信这是一个荒谬的基本错误 我只从 0 计算机背景学习 Oracle SQL 大约 4 个月 我计划在本月底学习 1z0 051 所以复习一下所有章节 在这个子句中 我试图获取工资高
  • 要嵌入 .NET 应用程序的 XPS 或 XAML 查看器?

    是否有查看器对象或 ActiveX 控件可用于在我的 NET 应用程序中嵌入 XPS 文档或 XAML GUI 您可以使用元素主机控制 http msdn microsoft com en us library system windows
  • 使用express模块​​时找不到模块“cookie”

    我需要你的帮助来使用express构建rest API 我已经尝试了很多版本的express 也有 CookieParser 中间件 但我刚刚收到上述错误 Error Cannot find module cookie at Functio
  • 无法在本地或远程找到“开发”或“主”分支。 - 语义gitversion

    我在 azure 中有一个存储库 它有默认分支 main 另外 我在 yml 文件中有一项用于语义版本控制的任务 task gittools gitversion gitversion task GitVersion 5 displayNa
  • TypeError:注册不是在React中使用React Hook Form的函数

    The Error Message If i dont use the Inputs inside div then it works perfectly but when i use Input inside div it shows m