簡體   English   中英

警報給出TypeError:這是未定義的

[英]Alert gives TypeError: this is undefined

我正在使用create-app一個React應用,並且正在注冊表格,目前只有兩個字段,一個用於電子郵件,一個用於密碼。

我正在做一個簡單的測試,我想通過使用警報來顯示輸入的值,如下所示:

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 | }

如何解決此錯誤?

您需要像在其他函數中一樣將其綁定在構造函數中。 在構造函數中添加:

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

您可以像這樣將函數綁定到構造函數中

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

或更改signIn()函數以使用Arrow函數

signIn = () => {

}

在按鈕標簽中更改

onClick={this.signIn} to {this.signIn.bind(this)}

要么

在構造函數中,添加

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

上面代碼中的錯誤是signIn函數缺少綁定。 因為在此函數中,您嘗試使用“ this”關鍵字訪問狀態變量。 但是由於您沒有在構造函數中綁定函數,因此缺少此作用域。 在構造函數中添加以下行this.signIn = this.signIn.bind(this); 它會工作。

您甚至可以嘗試以下綁定方式onClick = {this.signIn.bind(this)},這不是推薦的綁定方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM