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
相关产品推荐
相关产品推荐

