使用useForm() Hook时触发Uncaught TypeError: Cannot read properties of null (reading 'useRef')求助
解决函数组件中useForm()调用报错的问题
你代码里的核心问题是重复调用了两次useForm(),这会创建两个完全独立的表单实例,既违反React Hook的调用规则,也会导致表单状态混乱,引发报错。
修复步骤:
- 删除无用的
const form = useForm();行,这行代码没有被使用,还会生成多余的表单实例 - 只保留一次
useForm()调用,解构你需要的register、control等方法
修复后的完整代码:
import React from "react"; import "./form.css"; import { useForm } from "react-hook-form"; import { DevTool } from "@hookform/devtools"; function YoutubeForm() { // 只调用一次useForm(),解构所需方法 const { register, control } = useForm(); return ( <div className="form"> <form> <label htmlFor="username">User Name</label> <input type="text" id="username" {...register("username")}/> <label htmlFor="email">Email</label> <input type="text" id="email" {...register("email")} /> <label htmlFor="channel">Channel</label> <input type="text" id="channel" {...register("channel")} /> <button>SUBMIT</button> </form> <DevTool control={control} /> </div> ); } export default YoutubeForm;
另外补充一个代码里的小细节:第三个label的htmlFor属性写错成了password,已经在修复代码里修正为channel,保证和对应input的id匹配。
内容的提问来源于stack exchange,提问作者VijayRathod20
相关产品推荐
相关产品推荐

