RECT-清除电子邮件输入字段,表单提交后

发布于 2025-02-12 21:35:31 字数 2813 浏览 0 评论 0原文

提交表单后,密码字段输入被清空,而不是电子邮件输入字段。

正如您在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

After the form is submitted, the password field input is emptied, but not the email input field.

As you can see in the HandleSubmit function:
ref.current.value = ""; is what I've used as an attempt to clear the input fields after form submission, but it is only working for the password input field.

I've looked at a few other answers on SO, and I've tried e.target.reset(), and I've also tried setField(""); with no luck yet yet.


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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

北方的巷 2025-02-19 21:35:31

您将一个Ref设置为两个不同的字段。因此,只有最后一个是保留的,即密码一个(以及电子邮件字段的裁判被覆盖)为他们使用2种不同的裁判。如果可能的话,请参考您的表格,如果React-Bootstrap/表单支持它。

you are setting one ref to two different fields. Therefore only the last one is being retained i.e. password one (and email field's ref is being overwritten) use 2 different refs for them. Of if possible use ref to your form if react-bootstrap/form supports it.

情域 2025-02-19 21:35:31

您必须声明电子邮件和密码不同的变量。我更喜欢使用Usestate。

const [email, setEmail] = useState("");
const [password, setPassword] = useState("")

// Input
<Form.Control input value={email} type="email" placeholder="Enter email"  
        onChange={e => setEmail(e.target.value}
        isInvalid={!!errors.email} />
<Form.Control input value={password} type="password" placeholder="Password"  
        onChange={e => setPassword(e.target.value}
        isInvalid={!!errors.password} />

// handleSubmit
setEmail("");
setPassword("");

You have to declare different variable for email and password. I prefer just using useState.

const [email, setEmail] = useState("");
const [password, setPassword] = useState("")

// Input
<Form.Control input value={email} type="email" placeholder="Enter email"  
        onChange={e => setEmail(e.target.value}
        isInvalid={!!errors.email} />
<Form.Control input value={password} type="password" placeholder="Password"  
        onChange={e => setPassword(e.target.value}
        isInvalid={!!errors.password} />

// handleSubmit
setEmail("");
setPassword("");
天煞孤星 2025-02-19 21:35:31

React团队建议使用状态代替参考来声明写作表格。您已经将输入设置为“更改”时的输入,因此您可以通过将价值道具传递给输入来更容易地维护。

import React from 'react';
import Form from 'react-bootstrap/Form';
import { Button } from 'react-bootstrap';
import { Container } from 'react-bootstrap';
import { useState } from 'react';

const initialForm = {
  email: '',
  password: ''
};

export default function AllThis() {
  const [form, setForm] = useState(initialForm);
  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 handleSubmit = e => {
    e.preventDefault();
    const newErrors = findFormErrors();
    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
    } else {
      alert('Thank you for your feedback!');
      setForm(initialForm);
    }
  };

  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
            type="email"
            placeholder="Enter email"
            value={form.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
            type="password"
            placeholder="Password"
            value={form.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>
  );
}

https://codesandbox.io/s/reaect-clearing-email-email-input-field-field-form-submission-o41dki?file=/src/allthis.js.js

The React team recommends writing forms declaratively, using state instead of refs. You're already setting your inputs to state when they're changed, so you can solve this in an easier to maintain way by passing value props to your inputs.

import React from 'react';
import Form from 'react-bootstrap/Form';
import { Button } from 'react-bootstrap';
import { Container } from 'react-bootstrap';
import { useState } from 'react';

const initialForm = {
  email: '',
  password: ''
};

export default function AllThis() {
  const [form, setForm] = useState(initialForm);
  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 handleSubmit = e => {
    e.preventDefault();
    const newErrors = findFormErrors();
    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
    } else {
      alert('Thank you for your feedback!');
      setForm(initialForm);
    }
  };

  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
            type="email"
            placeholder="Enter email"
            value={form.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
            type="password"
            placeholder="Password"
            value={form.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>
  );
}

https://codesandbox.io/s/react-clearing-email-input-field-after-form-submission-o41dki?file=/src/AllThis.js

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文