类型错误:无法读取 null 的属性(读取“useRef”)

Aid*_*osh 12 typescript reactjs next.js react-hook-form

我正在使用 Next.js、TypeScript、sanity 和 tailwindcss。我尝试使用react-hook-form,但收到错误。

我试过了:

  • 将函数更改Post为箭头函数
  • 将函数更改Post为 const 函数
  • 将接口更改IFormInput为类型

这是错误所在:

  23 |      formState: { errors },
> 24 |  } = useForm<IFormInput>();
     |            ^
  25 | 
  26 |  return (
  27 |      <main>
Run Code Online (Sandbox Code Playgroud)

这是我在页面文件夹中的代码([slug].tsx):

import { useForm, SubmitHandler } from "react-hook-form";

interface IFormInput {
    _id: string;
    name: string;
    email: string;
    comment: string;
}

function Post({ post }: Props) {
 const { register, handleSubmit, formState: { errors } } = useForm<IFormInput>();

 return (
  <form>
   <input {...register("_id")} type="hidden" name="_id" value={post._id} />
   <input {...register("name", { required: true })} type="text"/>
   <input {...register("email", { required: true })} type="text" />
   <textarea {...register("comment", { required: true })} />            
   {errors.name && (<span>- The Name Field is required</span>)}
   {errors.comment && ( <span>- The Comment Field is required</span>)}
   {errors.email && ( <span>- The Email Field is required</span>)}
   <input type="submit" />
  </form>
 );
}
Run Code Online (Sandbox Code Playgroud)

非常感谢任何帮助。

小智 12

我遇到了同样的错误,因为我没有在正确的文件夹中安装“React Hook Form”,请确保它位于您的 package.json 中


Tah*_*ips 6

我为最近开始使用Next.js 13.

react-hook-form我在使用release时遇到了这个问题Next.js 13。我有以下配置:

const nextConfig = {
  experimental: {
    appDir: true,
  },
}
Run Code Online (Sandbox Code Playgroud)

appDir将值更改为 后false,问题就消失了。

  • 在你弄清楚之后发布这个,你就是一个救星。 (2认同)