使用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,如果没做这一步,也会导致handleSubmitundefined - 所有校验规则(required、minLength、maxLength、pattern等)都必须放在
register的第二个参数对象里,不能拆分传递
内容的提问来源于stack exchange,提问作者Amir Hadizadeh
相关产品推荐
相关产品推荐

