javascript - 错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。在 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;
对此的任何帮助都会很棒。
解决方案
推荐阅读
- java - 如何捕获在 paranthises 之间具有网络数学的正则表达式模式
- python - 使用 Python 将嵌套列表插入 mysql 数据库
- python - Python 到存储过程 - 要执行的第一个参数必须是字符串或 unicode 查询
- java - 在 Comparator 比较方法中调用方法
- ruby-on-rails - 在 Rails 5 模型的 default_scope 中使用包含方法,而不是在控制器中
- c# - 3 种地址的正则表达式
- java - 没有抽象类和接口的工厂方法
- html - 当我将鼠标悬停在盒子上时,我的内容是换行的,它是如何修复的?
- javascript - 带有 $sum 条件的 MongoDB 组聚合
- java - 如何每秒重绘一个组件?