出于某种原因,当我点击它们时,我的onClick处理程序正在向我的url添加一个空查询参数。我能够通过将event.preventDefault添加到我的事件处理程序来解决问题,但我想更好地了解实际发生的情况以及这是否是正确的解决方案。对于上下文,下面的代码是测试某些OAuth 2功能的简单组件。 onClick处理程序只会触发回流操作。你会看到我已经为所有人添加了e.preventDefault()。如果没有该修复,只要我触发其中一个功能,我的网址就会从http://localhost:3000/#/signIn更改为http://localhost:3000/?#/signIn。我也在使用react-router。
// dependencies -------------------------------------------------------
import React from 'react';
import hello from '../../libs/hello';
import Actions from '../../actions/Actions';
import UserStore from '../../stores/userStore';
var Signin = React.createClass({
// life cycle events --------------------------------------------------
componentDidMount: function () {
},
render: function () {
return (
<form>
<h2>Sign in with Google</h2>
<button className="btn btn-primary" onClick={this._signIn} >
<i className="fa fa-google" />
<span> Google</span>
</button>
<button className="btn btn-info" onClick={this._logToken} >Log Token</button>
<button className="btn btn-warning" onClick={this._signOut}>Sign Out</button>
</form>
);
},
// custom methods -----------------------------------------------------
_signIn: function (e) {
e.preventDefault();
Actions.signIn();
},
_signOut: function (e) {
e.preventDefault();
Actions.signOut();
},
_logToken: function (e) {
// e.preventDefault();
Actions.logToken();
}
});
export default Signin;
答案 0 :(得分:20)
button
代码的默认类型为submit
,这意味着点击button
会提交您的表单(将?
附加到您的网址)。
要修复您的示例,您可以将type="button"
添加到按钮&amp; /或将<form>
替换为<div>
/ <span>
(因为您的代码没有&#39} ; t似乎真的需要form
元素。
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button
可能的值是:
- submit:该按钮将表单数据提交给服务器。如果未指定属性,或者属性为
,则这是默认值 动态更改为空值或无效值。- reset:该按钮将所有控件重置为其初始值。
- 按钮:该按钮没有默认行为。它可以具有与元素事件相关联的客户端脚本 事件发生时触发。
答案 1 :(得分:7)
我很确定,因为您正在从表单中捕获按钮的单击,而没有preventDefault()表单正在发布。由于表单中没有输入,因此没有查询参数。由于表单没有指定POST方法,因此它正在向自己执行get请求,这会添加一个空查询字符串。使用preventDefault(),您将停止表单提交操作。