Reactjs: page refreshing upon `onClick` handle of Button?

牧云@^-^@ 提交于 2019-11-29 19:16:34

问题


I have the following block inside my render() (which is a Bootstrap Button: https://react-bootstrap.github.io/components.html#buttons-options):

<Button type="simpleQuery" onClick={this.handleEntailmentRequest.bind(this)}>
   Query
</Button>

and the following function:

handleEntailmentRequest() {
    console.log("handle request ");
}

Whenever I click on the button I can see that the the "handle request" question appears in the console log, but suddenly disappears. My understanding is that something is causing the page to refresh. Any opinons where I am going wrong?


回答1:


The default button action is to submit the form.

If you don't need that - you need to prevent that:

handleEntailmentRequest(e) {
    e.preventDefault();

    console.log("handle request ");
}

References:

  • MDN - Event.preventDefault()



回答2:


The full solution for the issue of the page reloading will be:

<Button type="simpleQuery" onClick={(e) => {this.handleEntailmentRequest(e)}}>
   Query
</Button>


handleEntailmentRequest(e){
    e.preventDefault();
    //do something...

}


来源:https://stackoverflow.com/questions/38256256/reactjs-page-refreshing-upon-onclick-handle-of-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!