Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
75 views
in Technique[技术] by (71.8m points)

javascript - React: this is null in event handler

I have a LoginForm component. I want to check before submit, that both loginName and password is set. I tried with this code (a lot of stuff omitted):

class LoginForm extends Component {

  constructor() {
    super();

    this.state = {
      error: "",

      loginName: "",
      password: "",
      remember: true
    };
  }


  submit(e) {
    e.preventDefault();
    if(!this.state.loginName || !this.state.password) { //this is null
      this.setState({ error: "Fill in both fields" });
    } else {
      console.log("submitting form");
    }
  }

  render() {
    return (
      <div className="col-xs-12 col-sm-6 col-md-4">
        <form className="login" onSubmit={this.submit}>
          <button type="submit" className="btn btn-default">Sign in</button>
        </form>
      </div>
    );
  }
}

export default LoginForm;

however, i get a TypeError in the event handler, saying that this is null.

What should I be doing?

question from:https://stackoverflow.com/questions/33631482/react-this-is-null-in-event-handler

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need set this for submit method because now this is undefined, for this operation you can use .bind

onSubmit={ this.submit.bind(this) }

Example

or you can use arrow function

onSubmit={ (e) => this.submit(e) }

Example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...