NextJS 14中useForm is not a function问题求助
解决NextJS 14中React Hook Form的「useForm is not a function」错误
以下是针对该错误的排查和解决步骤:
1. 检查useForm的导入方式
这是最常见的触发原因:React Hook Form v7+ 仅支持命名导入,如果误用默认导入就会报这个错。
错误导入:
import useForm from "react-hook-form";
正确导入:
import { useForm } from "react-hook-form";
2. 确认依赖版本兼容
NextJS 14要求React版本≥18.x,确保react-hook-form版本与React兼容,建议安装最新稳定版:
npm install react-hook-form@latest
如果用Zod resolver,也要同步更新:
npm install @hookform/resolvers@latest zod@latest
3. 清理重复依赖
项目中存在多版本react-hook-form会导致冲突,先查看依赖树:
npm ls react-hook-form
如果发现多个版本,执行去重命令:
npm dedupe
4. 检查自定义FormField组件
你代码中用到的FormField是自定义组件,要确保该组件内部没有错误导入useForm的情况,比如误用默认导入、重复导入不同版本等。
5. TypeScript配置排查(TS项目)
如果是TypeScript项目,确保tsconfig.json的模块解析配置正确:
{ "compilerOptions": { "moduleResolution": "node16", "esModuleInterop": true } }
完整正确代码示例
import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; // 定义Zod校验规则 const UserSchema = z.object({ email: z.string().email("请输入有效的邮箱地址"), }); type FormData = z.infer<typeof UserSchema>; export default function Home() { const { register, handleSubmit, formState: { errors }, } = useForm<FormData>({ resolver: zodResolver(UserSchema), }); const onSubmit = (data: FormData) => { console.log("提交的表单数据:", data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <div className="grid col-auto"> <input type="email" placeholder="Email" {...register("email")} /> {errors.email && <p style={{color: "red"}}>{errors.email.message}</p>} <button type="submit">Submit email</button> </div> </form> ); }
内容的提问来源于stack exchange,提问作者Antx
相关产品推荐
相关产品推荐

