首页 > 解决方案 > 错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。在 App.js 中使用 react-hook-form 时出错

问题描述

我是 React 的新手,我正在尝试使用 React 钩子表单在 App.js 中编写代码,但我一直遇到错误。我对应用程序的目标只是一个简单的注册表单,以便我可以将用户的数据保存到 JSON 中并将其保存到我的数据库中。React Hook Form 使这个过程非常简单,但我不知道如何使用钩子在两个 javascript 文件之间传递信息。

错误信息

目前,我的 App.js 看起来像

import React, {useState, useEffect} from 'react';
import {useForm} from "react-hook-form";
import SignUp from "./views/SignUp/SignUp";

const App = (props) => {

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


    return (
        <div>
            <SignUp

                register = {register}
                handleSubmit = {handleSubmit}
                errors = {errors}



            />

        </div>
    );
};


export default App;

我的 SignUp.js 看起来像

import React from 'react';

const SignUp = (props) => {




    const onSubmit = (data) => {

        console.log(data);
    };



    return (
        <form onSubmit={props.handleSubmit(onSubmit)}>
            <input type="text" placeholder="First name" name="First name" ref={props.register({required: true, maxLength: 80})} />
            <input type="text" placeholder="Last name" name="Last name" ref={props.register({required: true, maxLength: 100})} />
            <input type="datetime" placeholder="Date Of Birth" name="Date Of Birth" ref={props.register} />
            <input type="search" placeholder="Location of Birth" name="Location of Birth" ref={props.register} />
            <input type="time" placeholder="Time of Birth" name="Time of Birth" ref={props.register} />
            <input type="text" placeholder="Email" name="Email" ref={props.register({required: true, pattern: /^\S+@\S+$/i})} />
            <input type="tel" placeholder="Mobile number" name="Mobile number" ref={props.register({required: true, minLength: 6, maxLength: 12})} />
            <input type="text" placeholder="Username" name="Username" ref={props.register} />
            <input type="text" placeholder="Password" name="Password" ref={props.register} />
            <input type="submit" />

        </form>
    );

};

export default SignUp;

对此的任何帮助都会很棒。

标签: javascriptreactjsreact-hooks

解决方案


推荐阅读