首页 > 解决方案 > React Form hook - 尽管输入了输入,但仍收到“必填字段”错误消息

问题描述

我刚开始使用 react form hook 构建一个表单。刚从名为 name 的单个输入开始,当我提交表单时,我收到错误消息。

我尝试按照以下说明操作: https ://react-hook-form.com/get-started

//I have tried with this but I get unexpected token error:
 <input {...register('name', { required: true })} />

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



const NewUserForm = () => {
    const { register, handleSubmit,  formState: { errors } } = useForm();
    const onSubmit = data => console.log(data)


    return (

      <form onSubmit={handleSubmit(onSubmit)}>
        <input type="text" placeholder="Name" name="name" ref={register('name', {required: true})} />
        {errors.name && <span> This field is required</span>} 
     <input type="text" placeholder="Email" name="email" ref={register('email', {required: true})} />
        {errors.email && <span> This field is required</span>} 
        <input type="submit" />            
      </form>
    )
}

export default NewUserForm

标签: validationreact-hook-form

解决方案


推荐阅读