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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38256256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:14:50  来源:igfitidea点击:

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

javascriptreactjsreact-jsx

提问by Daniel

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

我的内部有以下块render()(这是一个 Bootstrap 按钮: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?

每当我单击按钮时,我都可以看到控制台日志中出现“处理请求”问题,但突然消失了。我的理解是某些原因导致页面刷新。我哪里出错了?

回答by zerkms

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:

参考:

回答by Roman

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

}

回答by SureN

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