如何使用 React Bootstrap 重置表单值

问题描述 投票:0回答:2

点击注册按钮后我的目标是:

  • 将输入字段设为空白
  • 不显示错误工具提示

这是CodeSandbox

我已经尝试使用 event.target.reset(); 但是工具提示仍然出现在屏幕上。

export default function App() {
  const [showSucessAlert, setshowSucessAlert] = useState(false);
  const [validated, setValidated] = useState(false);
  const [transitionAlert, setTransitionAlert] = useState(false);

  const handleSubmit = (event) => {
    const form = event.currentTarget;
    event.preventDefault();

    if (form.checkValidity() === false) {
      event.stopPropagation();
    } else {
      handleClickTransitionAlert();
      setshowSucessAlert(true);
    }
    setValidated(true);
  };

  const handleClickTransitionAlert = () => {
    setTransitionAlert(true);
    setTimeout(() => {
      setTransitionAlert(false);
    }, 1700);
  };

  return (
    <Form noValidate validated={validated} onSubmit={handleSubmit}>
      <Form.Group className="position-relative" controlId="validationPassword">
        <Form.Label>Password</Form.Label>
        <InputGroup hasValidation id="validationPassword" />
        <Form.Control
          type="password"
          aria-describedby="validationPassword"
          required
        />
        <Form.Control.Feedback tooltip type="invalid">
          Please enter your Password.
        </Form.Control.Feedback>
      </Form.Group>
      <Alert
        className={`mt-1 p-1 position-fixed ${
          transitionAlert ? "alert-shown" : "alert-hidden"
        }`}
        show={showSucessAlert}
        variant="success"
      >
        Registered user!
      </Alert>
      <Button className="mt-5" variant="primary" type="submit">
        Register
      </Button>
    </Form>
  );
}

这是CodeSandbox

欢迎任何帮助!

javascript reactjs react-bootstrap
2个回答
2
投票

我通常不使用不受控制的组件,但我认为你可以通过在

setValidated(false)
中添加
event.target.reset()
handleClickTransitionAlert
来解决这个问题,如下所示:

  const handleClickTransitionAlert = (event) => {
    setTransitionAlert(true);
    setTimeout(() => {
      setTransitionAlert(false);
      setValidated(false)
      event.target.reset()
    }, 1700);
  };

0
投票

尝试重置 Bootsrap Form 上已验证的属性。 它应该看起来像这样(这是伪代码):

import React, { useRef, useState } from 'react';
const FormComponent = () => {
  const [validated, setValidated] = useState(false);
  const formRef = useRef(null);

  const handleReset = () => {
    formRef.current.reset();
    setValidated(false);
  };

  const handleSubmit = () => {
     // Do stuff here
     // On success or error:
    setValidated(true);
    handleReset();
  }

   return(
      <Form ref={formRef}  validated={validated} onSubmit={handleSubmit}>
        // your form inputs
      </Form>
   );
export default FormComponent;
}
© www.soinside.com 2019 - 2024. All rights reserved.