reactjs 当onSubmit被调用时,react-hook-form不工作

dfuffjeb  于 2023-02-22  发布在  React
关注(0)|答案(3)|浏览(147)

当onSubmit被调用时,我的react-hook-form不工作。
这就是我的问题来自我假设:

const onSubmit = (data) =>{
        console.log(data);
        alert("Reserve Successful")
        reset()
    }

    return (
        
        <div className={styles.Reserve} id="form"> 
            
            <form onSubmit={handleSubmit(onSubmit)}>

完整代码:

import styles from "../styles/Form.module.css"
import { useForm } from "react-hook-form";
import { TimePicker, KeyboardDatePicker } from '@material-ui/pickers';
import { Select, MenuItem, InputLabel } from '@mui/material';
import { useState } from 'react';



function Form () {
    const [quantity, setQuantity] = useState("")

    const handleChange = (e) =>{
        setQuantity(e.target.value)
    }

    const [fecha, cambiarFecha ] = useState(new Date());

    const { register, formState:{ errors }, handleSubmit, reset } = useForm()
    // const {  } = useForm()
    
 
    const onSubmit = (data) =>{
        console.log(data);
        alert("Reserve Successful")
        reset()
    }

    return (
        
        <div className={styles.Reserve} id="form"> 
            
            <form onSubmit={handleSubmit(onSubmit)}> 

                <div className={styles.formContainer}>
                <h2 className={styles.form__h2} style={{textAlign:"center"}}>Book A Table</h2>
                    <div>
                        <label className={styles.label} >Name</label>
                        <input className={styles.input} style={{display:'flex', justifycontent:"center"}} name="" {...register("name", {
                            required: true,
                            minLength:2
                            
                            } )}/>
                            {errors.name?.type === "required" && <p className={styles.error__p}>The field must be completed to continue</p> }
                            {errors.name?.type === "minLength" && <p className={styles.error__p}>The field must have more than two letters</p>}
                    </div>

                    <div className={styles.sections} >
                        <label className={styles.label} >Last Name</label>
                        <input className={styles.input} style={{display:'flex', justifycontent:"center"}} name="" {...register("lastName", {
                            required: true
                        })} />
                        {errors.lastName?.type === "required" && <p className={styles.error__p}>The field must be completed to continue</p> }

                    </div>

                    <div>
                        <label className={styles.label} >Email</label>
                        <input className={styles.input} style={{display:'flex', justifycontent:"center" }} {...register("email", {
                            required: true,
                            pattern: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
                        })} />
                        {errors.email?.type === "required" && <p className={styles.error__p}>The field must be completed to continue</p> }
                        {errors.email?.type === "pattern" && <p className={styles.error__p}>The field must be completed a valid email</p> }
                    </div>
                        
                    <div>
                        <label className={styles.label} >Phone</label>
                        <input className={styles.input} style={{display:'flex', justifycontent:"center"}} {...register("phone", {
                            required: true,
                            pattern: /[0-9]/
                        })} />
                        {errors.phone?.type === "required" && <p className={styles.error__p}>The field must be completed to continue</p> }
                        {errors.phone?.type === "pattern" && <p className={styles.error__p}>The field must be completed with a valid phone</p> }
                    </div>

                    <div>
                        <label className={styles.label} >Date</label>
                        <KeyboardDatePicker style={{display:'flex', justifycontent:"center", marginBottom:15}} className={styles.picker} onChange={cambiarFecha} 
                        value={fecha}
                        format="MM/dd/yyyy"
                        variant="inline"
                        
                        {...register("date", {
                          
                        })} />
          
                    </div>

                    <div>
                        <label className={styles.label} >Time</label>
                        <TimePicker style={{display:'flex', justifycontent:"center", textAlign:"center", marginBottom:15}} className={styles.time} name="" min="09:00" max="18:00" {...register("time", {
                            required: true
                        })}/>
               
                    </div>

                    <div>
                    <InputLabel className={styles.label}>Attendees</InputLabel>
                        <Select  style={{ height: 40}} labelId="label" id="select" value={quantity} onChange={handleChange} displayEmpty fullWidth >
                            <MenuItem value="" disabled>Select Attendees</MenuItem>
                            <MenuItem value={1}>One</MenuItem>
                            <MenuItem value={2}>Two</MenuItem>
                            <MenuItem value={3}>Three</MenuItem>
                            <MenuItem value={4}>Four</MenuItem>
                        </Select>
            
                    </div>
                        
                    <button className={styles.Submit} type="submit" name=''>Reserve</button>
                        
                </div>
            </form>

export default Form

我尝试使用React-Hook-Form验证表单,但是HandleSubmit(onSubmit)不会发送包含验证的表单。
谢谢

ffscu2ro

ffscu2ro1#

请导入handlesubmit从hookform如下..

const {
    register,
    handleSubmit,
    reset,
    control,
    watch,
    trigger,
    formState: { errors, isDirty },
  } = useForm({
    mode: "onChange"
  });
djmepvbi

djmepvbi2#

嗨,你必须用react-hook-form提供的FormProvider Package 表单
像这样尝试

import { useForm, FormProvider } from 'react-hook-form';

function Form () {
...
const methods = useForm();
const { register, formState:{ errors }, handleSubmit, reset } = methods;

return (
<FormProvider {...methods}>
 <form onSubmit={handleSubmit(onSubmit)}> 

            <div className={styles.formContainer}>
            <h2 className={styles.form__h2} style={{textAlign:"center"}}>Book A Table</h2>
                <div>
                    <label className={styles.label} >Name</label>
                    <input className={styles.input} style={{display:'flex', justifycontent:"center"}} name="" {...register("name", {
                        required: true,
                        minLength:2
                        
                        } )}/>
                        {errors.name?.type === "required" && <p className={styles.error__p}>The field must be completed to continue</p> }
                        {errors.name?.type === "minLength" && <p className={styles.error__p}>The field must have more than two letters</p>}
                </div>

                <div className={styles.sections} >
                    <label className={styles.label} >Last Name</label>
                    <input className={styles.input} style={{display:'flex', justifycontent:"center"}} name="" {...register("lastName", {
                        required: true
                    })} />
                    {errors.lastName?.type === "required" && <p className={styles.error__p}>The field must be completed to continue</p> }

                </div>

                <div>
                    <label className={styles.label} >Email</label>
                    <input className={styles.input} style={{display:'flex', justifycontent:"center" }} {...register("email", {
                        required: true,
                        pattern: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
                    })} />
                    {errors.email?.type === "required" && <p className={styles.error__p}>The field must be completed to continue</p> }
                    {errors.email?.type === "pattern" && <p className={styles.error__p}>The field must be completed a valid email</p> }
                </div>
                    
                <div>
                    <label className={styles.label} >Phone</label>
                    <input className={styles.input} style={{display:'flex', justifycontent:"center"}} {...register("phone", {
                        required: true,
                        pattern: /[0-9]/
                    })} />
                    {errors.phone?.type === "required" && <p className={styles.error__p}>The field must be completed to continue</p> }
                    {errors.phone?.type === "pattern" && <p className={styles.error__p}>The field must be completed with a valid phone</p> }
                </div>

                <div>
                    <label className={styles.label} >Date</label>
                    <KeyboardDatePicker style={{display:'flex', justifycontent:"center", marginBottom:15}} className={styles.picker} onChange={cambiarFecha} 
                    value={fecha}
                    format="MM/dd/yyyy"
                    variant="inline"
                    
                    {...register("date", {
                      
                    })} />
      
                </div>

                <div>
                    <label className={styles.label} >Time</label>
                    <TimePicker style={{display:'flex', justifycontent:"center", textAlign:"center", marginBottom:15}} className={styles.time} name="" min="09:00" max="18:00" {...register("time", {
                        required: true
                    })}/>
           
                </div>

                <div>
                <InputLabel className={styles.label}>Attendees</InputLabel>
                    <Select  style={{ height: 40}} labelId="label" id="select" value={quantity} onChange={handleChange} displayEmpty fullWidth >
                        <MenuItem value="" disabled>Select Attendees</MenuItem>
                        <MenuItem value={1}>One</MenuItem>
                        <MenuItem value={2}>Two</MenuItem>
                        <MenuItem value={3}>Three</MenuItem>
                        <MenuItem value={4}>Four</MenuItem>
                    </Select>
        
                </div>
                    
                <button className={styles.Submit} type="submit" name=''>Reserve</button>
                    
            </div>
        </form>
</FormProvider>
)

}

nbewdwxp

nbewdwxp3#

由于我没有看到任何验证模式更新以上代码片段。有一个变化,你已经把验证,这是防止触发onSubmit。到目前为止,我看到你的代码,你可以请console.log(错误),你可能会发现,如果任何验证是触发和解决它相应的。

相关问题