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

前端 未结 4 1909
旧巷少年郎
旧巷少年郎 2021-01-02 00:30

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

&         


        
相关标签:
4条回答
  • 2021-01-02 00:35

    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()
    0 讨论(0)
  • 2021-01-02 00:36

    You can prevent the default behavior as suggested by zerkms or

    Just add type="button" in button tag.

    Eg: this.showSomething('all')}>All

    0 讨论(0)
  • 2021-01-02 00:44

    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...
    
    }
    
    0 讨论(0)
  • Yes! That did worked! If your react-app gets refreshed unexpectedly then, you should pass (e) as an event argument and then use e.preventDefault() in the function body which will prevent happen the default behavior of the onClick event.

    0 讨论(0)
提交回复
热议问题