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

react-hook-form验证错误信息不显示,console.log输出undefined如何解决

问题根因

  • 调用watch("example")监听的字段不存在:你的表单内没有name为example的输入项,因此打印结果为undefined
  • 错误提示判断逻辑错误:react-hook-form的errors对象的键与你调用register时传入的字段名一一对应,你注册的两个字段为email、vraag,因此验证失败后错误信息只会存放在errors.email、errors.vraag下,你写的errors.exampleRequired永远是假值,错误提示自然不会渲染。

修复后参考代码

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

export default function ContactForm() {
  const { register, handleSubmit, watch, formState: { errors } } = useForm();
  const onSubmit = data => console.log(data);

  // 不需要监听功能可直接删除该行,此处改为监听已存在的email字段做示例
  console.log(watch("email"));

  return (
    <div className="md:w-4/12 ml-auto mr-auto translate-x-1/2 mt-24 w-9/12">
        <form onSubmit={handleSubmit(onSubmit)} className="bg-red-500 p-4">
            <label className='text-lg'> email:</label>
            <input label="email" id="email" className="block w-full" {...register("email", {required: "邮箱为必填项"})} />
            {/* 对应email字段的错误提示 */}
            {errors.email && <span className="bg-yellow-400">{errors.email.message}</span>}
            
            <label className='text-lg mb-4'>vraag:</label>
            <textarea id="tekst" type="textarea" className="block box-border w-full h-52" {...register("vraag", { required: "内容为必填项" })} />
            {/* 对应vraag字段的错误提示 */}
            {errors.vraag && <span className="bg-yellow-400">{errors.vraag.message}</span>}
            
            <input type="submit" value="versturen" className="pl-2 mt-2 pr-2 block ml-auto mr-auto cursor-pointer"/>
        </form>
    </div>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 07:06:01