首页 > 解决方案 > 警报给出 TypeError:这是未定义的

问题描述

我正在制作一个反应应用程序create-app,我正在制作一个注册表格,它现在只有两个字段,一个用于电子邮件,一个用于密码。

我正在做一个简单的测试,我想通过使用警报来显示我输入的值,就像这样:

import React, { Component } from 'react';

class App extends Component {

  constructor(props) {
      super(props);
      this.state = {
        email:'',
        password:''
      };
      this.handleEmailChange = this.handleEmailChange.bind(this);
      this.handlePasswordChange = this.handlePasswordChange.bind(this);
  }

  handleEmailChange(e){
    this.setState({email:e.target.value})
  }
  handlePasswordChange(e){
    this.setState({password:e.target.value})
  }

  signIn(){
    alert('Email address is ' + this.state.email + ' Password is ' + this.state.password);
  }

  render() {
    return (
      <form className="form-signin">
                <h2 className="form-signin-heading"> Please sign in </h2>
                <label for="inputEmail" className="sr-only"> Email address</label>
                <input type="email" onChange={this.handleEmailChange} id="inputEmail" className="form-control" placeholder="Email address" required autofocus />
                <label for="inputPassword" className="sr-only"> Password</label>
                <input type="password" onChange={this.handlePasswordChange} id="inputPassword" className="form-control" placeholder="Password" required />
                <button className="btn btn-lg btn-primary btn-block"  onClick={this.signIn} type="button"> Sign in </button>
      </form>
    );
  }
}

export default App;

当我跑

npm start

我可以在 localhost 上看到我的应用程序,但是当我填写值并希望查看这些结果时,我收到此错误:

TypeError: this is undefined

  23 | signIn(){
> 24 |   alert('Email address is ' + this.state.email + ' Password is ' + this.state.password);
  25 | }

我怎样才能修复这个错误?

标签: javascriptreactjs

解决方案


您需要在构造函数中绑定它,就像使用其他函数一样。在构造函数中添加:

this.signIn= this.signIn.bind(this);

推荐阅读