[英]Input wont reset after form submission?
I am using email.js to send emails client side, and validator to validate the email and phone number.我正在使用 email.js 发送电子邮件客户端,并使用验证器来验证 email 和电话号码。 Everything works fine, except... I am trying to empty the input fields after a successful submission.
一切正常,除了......我试图在成功提交后清空输入字段。
Here is what I have so far:这是我到目前为止所拥有的:
State management: 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)
};
Validation and Submit handler:验证和提交处理程序:
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:形式:
<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>
QUESTION: How can I reset the input fields after submission?问题:提交后如何重置输入字段?
Setting the form refs value to null worked.将表单参考值设置为 null 有效。 Here is what I added to the
handleSubmit
function, after sending the email:这是我在发送 email 之后添加到
handleSubmit
function 的内容:
formRef.current[0].value = null
formRef.current[1].value = null
UPDATE This si the better way.更新这是更好的方法。 I added
value={inputValues.user_email}, value={inputValues.user_phone}, value={inputValues.user_message}
to each respective input field.我将
value={inputValues.user_email}, value={inputValues.user_phone}, value={inputValues.user_message}
添加到每个相应的输入字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.