2017-07-07 1558 views
0

在我的React/JS應用程序中。這是Component類我的一部分:這在一個函數中爲空,而不在另一個類中

<p> 
      <input 
       onChange={ this.handleEmailChange } value={ this.props.email } type='email' 
       className={ this.state.error ? 'form-control loginCredentialError shakeElement' : 'form-control' } 
       name='email' 
       placeholder='Email' required='True' 
      /> 
      <input 
       onChange={ this.handlePasswordChange } value={ this.props.password } type='password' 
       className={ this.state.error ? 'form-control loginCredentialError shakeElement' : 'form-control' } name='password' 
       placeholder='Password' required='True' 
      /> 
      </p> 
      <p> 
      <Button 
       onClick={ (event) => this.handleLoginClick(event) } 
       className='btn btn-round-lg btn-round btn-primary btn-block center-block' 
      >Sign In</Button> 
      </p> 

正如你可以看到我有handleEmailChangehandlePasswordChange,和handleLoginClick這三個功能是相同Component類作爲render功能

在這個函數中,this被評價爲null,這使得this.setState失敗。

handleEmailChange(event) { 
    const value = event.target.value; 
    console.log(value); 
    this.setState({ email: value }); 
    } 

然而,在此功能的this是微細且具有值。 setState效果很好。任何人都可以讓我知道爲什麼這些看似相似的功能有所不同?

handleLoginClick(event) { 
    event.preventDefault(); 

    const payload = { 
     'email': this.state.email, 
     'password': this.state.password, 
    }; 

    this.setState({ communicating: true, error: false, errorServer: false }); 
... 
... 
... 
+0

這是因爲返回handleLoginClick –

回答

3

這裏的區別在於綁定。如果你看看你如何設置按鈕和輸入的onChange,在一個你使用箭頭功能handleLoginClick和其他你使用{this.handleEmailChange}

箭頭功能自動綁定this給該函數。有兩種方法可以解決這個問題。或者:

onChange = {this.handleEmailChange.bind(this)} 

onChange = {(event) => handleEmailChange(event)} 

這將創建功能,您正在設置的狀態this之間的綁定。

退房:Difference of .bind() to arrow function() => usage in React更多信息使用箭頭功能或.bind()結合上下文

+0

啊箭頭的功能!是的...我忘記了約會。謝謝 ! – JasonGenX

+0

它讓我每一次! –

+0

綁定。那是。不會出現。 – JasonGenX

相關問題