简体   繁体   English

Reactjs:在按钮的“onClick”句柄上刷新页面?

[英]Reactjs: page refreshing upon `onClick` handle of Button?

I have the following block inside my render() (which is a Bootstrap Button: https://react-bootstrap.github.io/components.html#buttons-options ):我的render()中有以下块(这是一个引导按钮: https://react-bootstrap.github.io/components.html#buttons-options ):

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

and the following function:以及以下 function:

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

Whenever I click on the button I can see that 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?我哪里出错了?

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:参考资料:

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...

}

You can prevent the default behavior as suggested by zerkms or您可以按照 zerkms 或

Just add type="button" in button tag.只需在按钮标签中添加 type="button" 即可。

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

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.如果您的 react-app 意外刷新,您应该将 (e) 作为事件参数传递,然后在函数体中使用e.preventDefault() ,这将防止 onClick 事件的默认行为发生。

After adding the attribute type="button" in React solved my issue.在 React 中添加属性type="button"后解决了我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM