javascript - 即使单击提交按钮后也不会调用 onSubmit 函数
问题描述
我是 Reactjs 的新手。我刚写了这段代码,onSubmit 函数不起作用。如果是注册或表单句柄提交的错误,我没有得到。在写入表单标签的这一行中可能是错误的。
请指导并让我知道解决方案。react-hook-form 版本是 7.14
React 版本是 17.02
FieldArray.js
import React, { Fragment } from "react";
import { useForm } from "react-hook-form";
function FieldArray() {
const { register, handleSubmit } = useForm();
const basicform = (
<div className="card">
<div className="card-header">Basic Information</div>
<div className="card-body">
<div>
<div className="form-group">
<label htmlFor="fullname">Full Name</label>
<input
type="text"
className="form-control"
id="fullname"
name="fullname"
{...register("fullname")}
/>
</div>
<div className="form-group">
<label htmlFor="email">Email address</label>
<input
type="email"
className="form-control"
id="email"
name="email"
{...register("email")}
/>
</div>
<div className="form-group">
<label htmlFor="phone">Phone Number</label>
<input
type="text"
className="form-control"
id="phone"
name="phone"
{...register("phone")}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
className="form-control"
id="password"
name="password"
{...register("password")}
/>
</div>
</div>
</div>
</div>
);
const onSubmit = data => {
console.log('hjhhhh');
console.log(data);
}
return (
<div className="App">
<div className="container py-5">
<form onSubmit={handleSubmit(onSubmit)}>{basicform}</form>
<button className="btn btn-primary" type="submit">Submit</button>
</div>
</div>
);
}
export default FieldArray;
解决方案
我们必须将提交按钮包裹在 Form 标签内
<form onSubmit={handleSubmit(onSubmit)}>
{basicform}
<button className="btn btn-primary" type="submit">
Submit
</button>
</form>
沙盒 - https://codesandbox.io/s/silly-cori-t94eu?file=/src/react-hook-form.jsx
推荐阅读
- angular - 从抽象类继承角度组件与抽象组件有什么区别?
- php - 如果值已经在数据库中,则禁用复选框
- java - 如何在微调器中实现微调器?
- javascript - 如果不先使用 Chrome 开发工具检查元素,则无法在 Google Chrome 控制台中选择 DOM 元素
- android-navigation - 为什么在将 'androidx.navigation:navigation-ui' 添加为依赖项之前,getOnBackPressedDispatcher() 方法仍未解决?
- visual-c++ - 将字符串转换为 BSTR
- javascript - 条件 ng-click 中的函数和变量赋值
- haskell-stack - 停止“堆栈安装”构建没有 exe 依赖的内部库?
- python - 查找 scipy.ndimage 的 gaussian_filter 使用的权重或内核
- reactjs - 使用自定义请求标头反应传单 WMSTileLayer