类型错误:无法读取未定义的属性“消息”---使用 react-hook-form

时间:2021-05-11 11:36:12

标签: react-hook-form

我试图在消息输入表单中没有输入任何内容时显示错误消息,但是当我加载页面时,我收到此错误“类型错误:无法读取未定义的属性“消息””。我正在使用 react-hook-forms。这是我下面的代码。

import { Button } from "@material-ui/core";
import { Close } from "@material-ui/icons";
import React from "react";
import { useForm } from "react-hook-form";
import "./SendMail.css";

const SendMail = () => {
  const { register, handleSubmit, watch, errors } = useForm();

  const onSubmit = (formData) =>{
    console.log(formData)
  }


  return (
    <div className="sendMail">
      <div className="sendMail__header">
        <h3>New Message</h3>
        <Close className="sendMail__close" />
      </div>
      <form onSubmit={handleSubmit(onSubmit)}>
        <input name='to' placeholder="To" type="text" {...register('to',{required:true})}/>
        
        <input name="subject" placeholder="Subject" type="text" {...register('subject',{required:true})} />
        
        <input
          name="message"
          placeholder="Message..."
          type="text"
          className="sendMail__message"
          {...register('message',{required:true})}
        />
        {errors.message && <p>To is required!!</p>}

        <div className="sendMail__send">
          <Button
            className="sendMail__send"
            variant="contained"
            color="primary"
            type="submit"
          >
            Send
          </Button>
        </div>
      </form>
    </div>
  );
};

export default SendMail;

1 个答案:

答案 0 :(得分:1)

从 v7 开始,errors 对象移动到了 formState 属性,因此您需要调整您的析构:

const { register, handleSubmit, watch, formState: { errors } } = useForm();