簡體   English   中英

在本地反應中的onPress事件期間,this.state未定義

[英]this.state is undefined during onPress event in react native

你好我是新的反應本機,我的代碼是:

 import React, { View, Text, TextInput, Component } from 'react-native'; import Style from './styles/signin'; import Button from '../common/button'; export default class SignIn extends Component { constructor(props) { super(props); this.state = { email: '', password: '' }; } render(){ return( <View style={Style.container}> <Text style={Style.label}>Email</Text> <TextInput style={Style.input} onChangeText={(text) => this.setState({email: text})} value={this.state.email} /> <Text style={Style.label}>Password</Text> <TextInput style={Style.input} onChangeText={(text) => this.setState({password: text})} value={this.state.password} secureTextEntry={true} /> <Button text={'Sign in'} onPress={this.onPress}/> </View> ); } onPress(){ console.log(this.state.email); } } 

當我填寫此表單並按下登錄時,我有此錯誤消息:“無法讀取未定義的屬性'電子郵件'”。 感謝您的幫助!

這是一個約束性問題。 最簡單的解決方案是更改按鈕標記的JSX,如下所示:

<Button text={'Sign in'} onPress={this.onPress.bind(this)} />

ES6類失去了你可能習慣使用es5 react.createClass的自動綁定。 當使用ES6作為反應組分時,您必須更加意識到您的綁定。

另一種選擇是在構造函數中綁定方法,如下所示:

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

    this.onPress = this.onPress.bind(this)
  }

或者您甚至可以使用胖箭頭es6語法函數來維護與您正在創建的組件的“this”綁定:

<Button text={'Sign in'} onPress={() => this.onPress()} />

更新:

要再次更新,如果您的環境支持某些ES7功能(我相信本身是使用react-native initcreate-react-native-app shoudl構建的),您可以使用此表示法自動綁定使用的類方法this關鍵字。

// This is auto-bound so `this` is what you'd expect
onPress = () => {
    console.log(this.state.email);
};

代替

// This is not auto-bound so `this.state` will be `undefined`
onPress(){
  console.log(this.state.email);
}

最好的選擇是使用ES7功能(如果可用)或在構造函數中綁定。 直接在Button上使用匿名函數onPress={() => this.onPress()}onPress={this.onPress.bind(this)}對於性能原因不太有利。

暫無
暫無

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

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