繁体   English   中英

表单提交后输入不会重置?

[英]Input wont reset after form submission?

我正在使用 email.js 发送电子邮件客户端,并使用验证器来验证 email 和电话号码。 一切正常,除了......我试图在成功提交后清空输入字段。

这是我到目前为止所拥有的:

State 管理:

    const formRef = useRef()
    const [emailError, setEmailError] = useState('')
    const [phoneError, setPhoneError] = useState('')


    const [inputValues, setInputValues] = useState({email: "", phone: ""})
    const handleOnChange = event => {
        const { name, value } = event.target;
        setInputValues({ ...inputValues, [name]: value });
        validateEmail(inputValues.email)
        validatePhone(inputValues.phone)
    };

验证和提交处理程序:

    const validateEmail = (email) => {
        if (validator.isEmail(email)) {
            setEmailError('Valid Email :)')
            return true
        } else {
            setEmailError('Enter valid Email!')
             return false
        }
       
    }
    const validatePhone = (phone) => {
        if (validator.isMobilePhone(phone)) {
            setPhoneError('Valid Phone :)')
            return true
        } else {
            setPhoneError('Enter valid Phone!')
            return false
        }
    }

    const handleSubmit = (e) => {
        e.preventDefault()

        const isValidEmail = validateEmail(e.target.email.value)
        const isValidPhone = validatePhone(e.target.phone.value)

        if(isValidEmail && isValidPhone){
            console.log("if both inputs are true, on to submit")

            setSentMessage(false)
       
            //shouldnt this line empty out the current fields?
            setInputValues({email: "", phone: ""})
        } else {
            console.log("one of the inputs is false, wont submit")
        }
    }

形式:

<form ref={formRef} onSubmit={handleSubmit} className={classes.contactPageInputs}>

                <input placeholder='email' type="text" id="userEmail" name="email" onChange={(e) => handleOnChange(e)}></input>
                    <span style={{fontWeight: 'bold', color: 'red' }}>{emailError}</span>
                <input placeholder='phone' id="userPhone" name="phone" onChange={(e) => handleOnChange(e)}></input> <br />
                    <span style={{fontWeight: 'bold', color: 'red' }}>{phoneError}</span>
                <button className={classes.submitButton}>submit</button>
</form>

问题:提交后如何重置输入字段?

将表单参考值设置为 null 有效。 这是我在发送 email 之后添加到handleSubmit function 的内容:

formRef.current[0].value = null
formRef.current[1].value = null

更新这是更好的方法。 我将value={inputValues.user_email}, value={inputValues.user_phone}, value={inputValues.user_message}添加到每个相应的输入字段。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM