React中的表单行为不符合预期

时间:2016-10-12 20:28:23

标签: javascript reactjs ecmascript-6 react-router parse-react

我在React中有一个用于登录我的应用程序的表单。用于登录的代码本身很好,但是当您第一次加载页面并输入登录信息并单击“提交”时,登录的代码将触发,但页面将重新加载并显示一个空白表单。再次输入登录凭据时,它会按预期运行,但会启动另一个会话。对我做错了什么的想法?

import React from "react";
import ReactDOM from "react-dom";
import Router from "react-router";
import { Alert, Button, ControlLabel, FieldGroup, FormControl, FormGroup } from "react-bootstrap";

var Parse = require('parse');
var ParseReact = require('parse-react');
var ParseComponent = ParseReact.Component(React);
var mylogin;

export default class Login extends ParseComponent {
  constructor(props) {
    super(props);
    this.login = this.login.bind(this);
    mylogin = this;
  }

  observe(props, state) {
    return {
      user: ParseReact.currentUser
    };
  }

  static contextTypes = {
    router: React.PropTypes.object.isRequired
  }

  static defaultProps = {
    error: null
  }

  state = {
    error: this.props.error,
  }

  login() {
    var self = this;
    var username = ReactDOM.findDOMNode(this.refs.username).value;
    var password = ReactDOM.findDOMNode(this.refs.password).value;
    function error() {
      self.setState({ error: "Incorrect username or password" });
    }
    if (username.length && password.length) {
      Parse.User.logIn(username,password).then(function(success) {
        // Successful Login. Redirect to Dashboard.
        mylogin.context.router.push("/dashboard");
      }, function(err) {
        // Log-in error.
        error();
      });
    } else {
      this.setState({ error: "Please enter all fields" });
    }
  }

  render () {
      return (
          <div class="container" style={marginStyle}>
            <form>
              {
                this.state.error ?
                <Alert bsStyle="danger">
                  {this.state.error}
                </Alert> :
                null
              }
              <FormGroup controlId="username">
                <ControlLabel>Username</ControlLabel>
                <FormControl type="text" ref="username" placeholder="Username" />
              </FormGroup>
              <FormGroup controlId="password">
                <ControlLabel>Password</ControlLabel>
                <FormControl type="password" ref="password" placeholder="Password" />
              </FormGroup>
              <Button onClick={this.login} type="submit">
                Login
              </Button>
            </form>
          </div>
        );
      }
    }

1 个答案:

答案 0 :(得分:2)

按钮类型=“提交”的默认表单行为是实际提交表单。你需要阻止这个动作。登录的第一个参数应该是事件,您可以在其上调用event.preventDefault

...

login( e ) {
  e.preventDefault();
  var self = this;
  var username = ReactDOM.findDOMNode(this.refs.username).value;
  var password = ReactDOM.findDOMNode(this.refs.password).value;
  function error() {

...

请注意,我不太熟悉类语法(我是一个createClass粉丝),但这是你所描述的解决方案。事件对象e是否实际上可以在类语法中立即访问,我不确定。

修改:更好的是,尝试将onClick操作从按钮移至onSubmit上的<form>。然后像我上面描述的那样阻止默认。

Here's more from the docs