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

使用react-hook-form调用handleSubmit时出现undefined错误求助

问题解决:react-hook-form调用handleSubmit出现undefined错误

核心问题分析

你写的代码里有两个关键错误:

  • register函数的参数格式不对,校验规则应该合并成一个对象传递,你把pattern单独拆成第三个参数了,这不符合react-hook-form的API规范
  • 原生input标签不需要加control属性,control是给Controller组件用的,用register的话完全不需要这个属性

修正后的完整代码示例

import { useForm } from "react-hook-form";

function PhoneInput() {
  // 正确解构useForm的返回值
  const { register, handleSubmit } = useForm();

  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        type="tel"
        {...register("phoneSignIn", {
          required: true,
          minLength: 10,
          maxLength: 11,
          pattern: "[0-9]+" // 把pattern合并到校验规则对象里
        })}
        // 移除多余的control属性
      />
      <button type="submit">提交</button>
    </form>
  );
}

额外注意点

  • 确保你已经正确调用了useForm()并解构出register和handleSubmit,如果没做这一步,也会导致handleSubmit undefined
  • 所有校验规则(required、minLength、maxLength、pattern等)都必须放在register的第二个参数对象里,不能拆分传递

内容的提问来源于stack exchange,提问作者Amir Hadizadeh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 23:20:33