You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Next.js中Form的onSubmit失效,点击提交无Alert弹窗问题求助

解决Next.js中react-hook-form提交不触发Alert的问题

问题原因

你的代码没有使用react-hook-form的register方法为表单输入框注册字段,react-hook-form需要通过注册字段来跟踪表单状态,未注册字段会导致handleSubmit无法正常触发回调函数。另外,虽然按钮默认类型为submit,但显式声明能避免潜在的样式或逻辑冲突。

修复后的代码

import Head from 'next/head'
import Image from 'next/image'
import { Inter } from '@next/font/google'
import styles from '@/styles/Home.module.css'
const inter = Inter({ subsets: ['latin'] })
import { useForm } from "react-hook-form";

export default function Home() {
  const { handleSubmit, register } = useForm(); // 解构获取register方法

  const checkauth = (data: any) => {
    alert("Hello world");
    console.log(data); // 可选:打印表单数据验证是否成功获取
  };
  
  return (
    <div className="container">
      <div className="screen">
        <div className="screen__content">
          <form className="login" onSubmit={handleSubmit(checkauth)}>
            <div className="login__field">
              <i className="login__icon fas fa-user" />
              <input
                type="text"
                className="login__input"
                placeholder="User name / Email"
                {...register('username')} // 注册用户名字段
              />
            </div>
            <div className="login__field">
              <i className="login__icon fas fa-lock" />
              <input
                type="password"
                className="login__input"
                placeholder="Password"
                {...register('password')} // 注册密码字段
              />
            </div>
            <button type="submit" className="button login__submit"> {/* 显式设置提交类型 */}
              <span className="button__text">Log In Now</span>
              <i className="button__icon fas fa-chevron-right" />
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}

额外验证步骤

  • 确认已安装react-hook-form:若未安装,执行npm install react-hook-form或yarn add react-hook-form。
  • 查看浏览器控制台是否有报错,依赖缺失、语法错误等问题也会导致提交逻辑失效。

内容的提问来源于stack exchange,提问作者virat sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 16:01:28