首页 > 解决方案 > 即使单击提交按钮后也不会调用 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;

标签: javascriptreactjsmaterial-uireact-hook-form

解决方案


我们必须将提交按钮包裹在 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


推荐阅读