出于某种原因,我的 onClick 处理程序在我单击它们时向我的 url 添加了一个空查询参数。我能够通过将 event.preventDefault 添加到我的事件处理程序来解决这个问题,但我想更好地了解实际发生的事情以及这是否是正确的解决方案。对于上下文,下面的代码是一个简单的组件,用于测试一些 OAuth 2 功能。 onClick 处理程序只是触发回流操作。您会看到我已将 e.preventDefault() 添加到所有这些。如果没有这个修复,只要我触发其中一个功能,我的 url 就会从 http://localhost:3000/#/signIn 改变。至 http://localhost:3000/?#/signIn .我也在使用 react 路由器。
// 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;
最佳答案
默认类型 button
标签是 submit
这意味着点击 button
将提交您的表单(将 ?
附加到您的网址)。
要修复您的示例,您可以添加 type="button"
到你的按钮和/或更换你的<form>
用<div>
/<span>
(因为您的代码似乎并不真的需要 form
元素)。
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button
Possible values are:
- submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is
dynamically changed to an empty or invalid value.- reset: The button resets all the controls to their initial values.
- button: The button has no default behavior. It can have client-side scripts associated with the element's events, which are triggered when the events occur.
关于javascript - 为什么 React onClick 事件会在我的网址上附加一个问号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30491742/