首页 > 解决方案 > useForm 在既不是 React 函数组件的函数中被调用...错误

问题描述

下面的代码是最奇怪的错误。

/src/components/competitions/TheVaultform.js 第 5 行:React Hook “useForm”在函数“contactform”中被调用,该函数既不是 React 函数组件也不是自定义 React Hook 函数 react-hooks/rules-of-hooks

搜索关键字以了解有关每个错误的更多信息。

我刚刚安装了 react-hook-form 并运行了演示代码。

import React from 'react';
import { useForm } from 'react-hook-form';

export default function contactform() {
  const { register, handleSubmit, errors } = useForm();
  const onSubmit = data => console.log(data);
  console.log(errors);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input type="text" placeholder="First name" name="First name" ref={register({required: true, maxLength: 80})} />
      <input type="text" placeholder="Last name" name="Last name" ref={register({required: true, maxLength: 100})} />
      <input type="text" placeholder="Email" name="Email" ref={register({required: true, pattern: /^\S+@\S+$/i})} />
      <input type="tel" placeholder="Mobile number" name="Mobile number" ref={register({required: true, minLength: 6, maxLength: 12})} />
      <select name="Title" ref={register({ required: true })}>
        <option value="Mr">Mr</option>
        <option value="Mrs">Mrs</option>
        <option value="Miss">Miss</option>
        <option value="Dr">Dr</option>
      </select>

      <input name="Developer" type="radio" value="Yes" ref={register({ required: true })}/>
      <input name="Developer" type="radio" value="No" ref={register({ required: true })}/>

      <input type="submit" />
    </form>
  );
}

标签: reactjsreact-hook-form

解决方案


它无法识别 React 组件,因为它应该以大写字母开头,因此将您的组件更改为:

export default function ContactForm() { ...

推荐阅读