最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React onClick setState then run function - Stack Overflow

programmeradmin0浏览0评论

Good day!

Is it possible to trigger multiple functions on the onClick event ?

I would like when the user clicks on my button to setState and then run a function. I managed to update my state but I am not sure how to proceed to add the second step which would be to run my function called "goToOrderTemplate()"

<button
  type="button"
  className="btn btn-primary"
  style={{ width: 250 }}
  onClick={() =>
    this.setState({
      auth: this.passwordValidation()
    })
  }
>

Any help woul dbe greatly appreciated!

Good day!

Is it possible to trigger multiple functions on the onClick event ?

I would like when the user clicks on my button to setState and then run a function. I managed to update my state but I am not sure how to proceed to add the second step which would be to run my function called "goToOrderTemplate()"

<button
  type="button"
  className="btn btn-primary"
  style={{ width: 250 }}
  onClick={() =>
    this.setState({
      auth: this.passwordValidation()
    })
  }
>

Any help woul dbe greatly appreciated!

Share Improve this question asked Mar 2, 2019 at 22:19 KevKev 1091 gold badge3 silver badges6 bronze badges 1
  • Why not just do it after the setState ?, if you need to wait for the setState to perform, there is a second parameter callback function to setState. But you should use it in last case. – Dimitri Kopriwa Commented Mar 2, 2019 at 22:21
Add a ment  | 

2 Answers 2

Reset to default 5

setState takes a second parameter, which is a callback that gets called back when the state was set. You should use that if goToOrderTemplate depends on the state being set:

this.setState({
  auth: this.passwordValidation(),
}, goToOrderTemplate)

In the general case that you want to call two functions, just do that:

onClick={() => { 
  this.setState({
    auth: this.passwordValidation(),
  });
  goToOrderTemplate();
}}

You can pass a callback function to the this.setState as second argument

this.setState({
  auth: this.passwordValidation()
}, () => {
  goToOrderTemplate()
})
发布评论

评论列表(0)

  1. 暂无评论