为什么 React onClick 事件会在我的 url 后附加一个问号?

Why does a react onClick event append a question mark to my url?

出于某种原因,当我单击它们时,我的 onClick 处理程序向我的 url 添加了一个空查询参数。我能够通过将 event.preventDefault 添加到我的事件处理程序来解决问题,但我想更好地了解实际发生的事情以及这是否是正确的解决方案。对于上下文,下面的代码是一个简单的组件,用于测试一些 OAuth 2 功能。 onClick 处理程序只是触发回流操作。您会看到我已将 e.preventDefault() 添加到所有这些。如果没有这个修复,只要我触发其中一个函数,我的 url 就会从 http://localhost:3000/#/signIn to 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;

我很确定,因为您正在捕获表单中的按钮点击,而没有 preventDefault() 表单正在发布。由于表单中没有输入,因此没有查询参数。由于表单未指定 POST 方法,因此它正在向自身执行获取请求,这会添加一个空查询字符串。使用 preventDefault() 您将停止表单提交操作。

button 标签的默认类型是 submit,这意味着单击 button 将提交您的表单(将 ? 附加到您的 url ).

要修复您的示例,您可以将 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.