表单提交后,密码字段输入被清空,但电子邮件输入字段不被清空。
正如您在 HandleSubmit 函数中看到的: ref.current.value = "";是我在表单提交后尝试清除输入字段的方法,但它仅适用于密码输入字段。
我看过一些其他答案,我尝试过 e.target.reset(),我也尝试过 setField("");还没有运气。
import React from 'react';
import Form from 'react-bootstrap/Form';
import { Button } from 'react-bootstrap';
import { Container } from 'react-bootstrap';
import { useState } from 'react';
import { useRef } from 'react';
const allThis = () => {
const [form, setForm] = useState({})
const [errors, setErrors] = useState({})
const setField = (field, value) => {
setForm({
...form,
[field]: value
})
// Check and see if errors exist, and remove them from the error object:
if (!!errors[field]) setErrors({
...errors,
[field]: null
})
}
const ref = useRef(null); // set up empty field
const handleSubmit = (e) => {
e.preventDefault();
const newErrors = findFormErrors()
if (Object.keys(newErrors).length > 0) {
setErrors(newErrors)
} else {
alert('Thank you for your feedback!');
ref.current.value = ""; // empty the field
}
}
const findFormErrors = () => {
const { email, password } = form
const newErrors = {};
if (!email || email === '') newErrors.email = 'cannot be blank!';
/* else if (email.length > 30) newErrors.email = 'email is too long!'; */
if (!password || password === " ") newErrors.password = "cannot be blank";
return newErrors
}
return (
<Container>
<Form className="reduceForm">
<Form.Label className="contact">Contact Me</Form.Label>
<Form.Group className="mb-3" controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control input ref={ref} type="email" placeholder="Enter email"
onChange={e => setField('email', e.target.value)}
isInvalid={!!errors.email} />
<Form.Control.Feedback type='invalid'>
{errors.email}
</Form.Control.Feedback>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control input ref={ref} type="password" placeholder="Password"
onChange={e => setField('password', e.target.value)}
isInvalid={!!errors.password} />
<Form.Control.Feedback type='invalid'>
{errors.password}
</Form.Control.Feedback>
</Form.Group>
<Button onClick={handleSubmit} variant="primary" type="submit">
Submit
</Button>
</Form>
</Container>
)
}
export default allThis
最佳答案
您正在将一个引用设置为两个不同的字段。因此,只有最后一个被保留,即密码一(并且电子邮件字段的引用被覆盖)使用 2 个不同的引用。如果可能的话,如果react-bootstrap/form支持的话,请使用对您的表单的引用。
关于javascript - React - 表单提交后清除电子邮件输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72837072/