【问题标题】:TypeError: Cannot read properties of null (reading 'useRef')TypeError:无法读取 null 的属性(读取“useRef”)
【发布时间】:2022-06-10 17:53:02
【问题描述】:

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

我试过了:

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

这是错误所在:

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

这是我在 pages 文件夹中的代码 ([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>
 );
}

非常感谢任何帮助。谢谢!

【问题讨论】:

  • 你在使用 React 18 吗?如果是这样,你可以试试 React 17 吗?
  • 是的,我正在使用 react 18。
  • 发现挑战切换到反应 17
  • 不要降级反应 17 你也需要降级 Next。唯一看起来您的表单丢失的是 onSubmit 处理程序。尝试添加表单提交处理程序。 const onSubmit = async ({values}) =&gt; {console.log(values)} &lt;form onSumbit={handleSubmit(onSubmit)}&gt;...

标签: javascript typescript next.js tailwind-css sanity


【解决方案1】:

说它无法读取 useRef 意味着它没有找到 React。如果您没有 Node.js 的稳定版本,则可能会出现此问题,目前为v16.15.1,您可以在官方doc 上看到。如果是这种情况,请确保将其降级,为此您可以使用来自npmn 包:

npm i -g n
n stable
# if one of the commands does not pass, you may need to use sudo
sudo npm i -g n
sudo n stable

如果您使用的是yarn,请删除node_moduespackage-lock.jsonyarn.lock。然后启动你的开发服务器:

rm -rf node_modules package-lock.json yarn.lock
npm install
npm run dev

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 2021-12-04
    • 2021-12-17
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 2023-01-14
    相关资源
    最近更新 更多