【问题标题】:React.js, timeout - how to hide a div after a few secondsReact.js,超时 - 如何在几秒钟后隐藏 div
【发布时间】:2020-10-19 15:15:14
【问题描述】:

我正在使用 react.js 制作表单。我试图让一个 div 出现,然后在提交表单后消失。我怎样才能正确地做到这一点?

我的代码目前只是在提交表单后将我带到一个空白页面。

根据要求更新

  constructor(props) {
    super(props)
    this.state = {
      messageConfirm: ''
    }

    this.handleInput1 = this.handleInput1.bind(this);
    this.handleInput2 = this.handleInput2.bind(this);
    this.handleInput3 = this.handleInput3.bind(this);
    this.sendEmail = this.sendEmail.bind(this)
    this.submitForm = this.submitForm.bind(this)
  }

  resetForm() {
   //reset form
  }

  validateForm() {
    //validate form method
  }

  sendEmail(e) {
  //send email method
  }

  confirmEmailMessage(){
    this.setState({messageConfirm: "Thanks for your message"})
  }

  setTimeOut(){
    this.setState({messageConfirm: ""}, 5000)
  }
  
  
  submitForm(e) {
    e.preventDefault();
    const isValid = this.validateForm();
    if (isValid) {
      // this.sendEmail(e)
      this.confirmEmailMessage()
      this.setTimeOut()
      e.target.reset()
      this.resetForm()
    }
  }

  render() {
    return (
      <div className="container">
        <div className="contact-form container-fluid d-flex justify-content-center bd-highlight" id="contact-form">
          <form onSubmit={this.submitForm} data-testid="form">
            //form code
          </form>
        </div>
        <div>
        </div>
      </div>
    )
  }
}

【问题讨论】:

  • 您好,请提供您的组件代码的Minimal, Complete, and Reproducible,其中包含复制步骤和您已完成的任何调试细节。尝试将 SO 问题限制在单个特定问题上。
  • @DrewReese 这有帮助吗?
  • 啊,不,但实际上我最初误读了您的代码以及它试图做什么。我可以帮助解决更新消息状态的问题,但需要查看更多(可能是全部)组件,以了解在提交表单后它会呈现空白页的内容或原因。
  • @DrewReese Ive 刚刚更新了我的问题以显示大部分组件。感谢您花时间查看。
  • 太好了,因为我没有看到现有代码 sn-p 中描述的行为可能发生的方式,我正要创建一个代码沙盒来看看我是否可以。干杯。

标签: reactjs forms timeout


【解决方案1】:

React 的this.setState 的第二个参数是回调函数,而不是静态值。您可能打算通过回调调用setTimeout 来更新状态。我还建议将 your 函数的名称更改为更有意义的名称,例如 resetMessage,这样它就不会那么模棱两可了。然后为了完成主义者的缘故,您应该保存计时器 ref 并在组件卸载时将其清除,这样您就不会尝试设置已卸载组件的状态。

constructor(props) {
  super(props)
  this.state = {
    messageConfirm: '',
  };
  this.timerId = null;
}

resetMessage() {
  this.timerId = setTimeout(() => {
    this.setState({ messageConfirm: "" });
     this.timerId = null;
  }, 5000);
}

submitForm(e) {
  e.preventDefault();
  const isValid = this.validateForm();

  if (isValid) {
    this.confirmEmailMessage();
    this.resetMessage();
    e.target.reset();
    this.resetForm();
  }
}

...

componentWillUnmount() {
  cleatTimeout(this.timerId);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多