javascript - 为什么 React onClick 事件会在我的网址上附加一个问号?

标签 javascript reactjs postback

出于某种原因,我的 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/

相关文章:

javascript - 即使页面已经打开,如果 JavaScript 被禁用,如何使 div 突然显示

html - 下拉菜单在 overflowY 设置为自动时有很多中断

javascript - 从react js中的子文件夹导入模块

ASP.Net 回发 get 时找不到指定的 URL

c# - 是否可以在回发时伪造查询字符串?

asp-classic - 回发后下拉不保留选定的值

javascript - 将 0 放入 FOR 循环中会返回不需要的结果

javascript - 无 Action 的工作形式

javascript - React 通量拦截器实现

javascript - 从源代码构建 WysiHat?