在本地反应中的onPress事件期间,this.state未定义

ImP*_*LsE 10 javascript reactjs

你好我是新的反应本机,我的代码是:

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

当我填写此表单并按下登录时,我有此错误消息:"无法读取未定义的属性'电子邮件'".感谢您的帮助!

jma*_*rje 21

这是一个约束性问题.最简单的解决方案是更改按钮标记的JSX,如下所示:

<Button text={'Sign in'} onPress={this.onPress.bind(this)} />
Run Code Online (Sandbox Code Playgroud)

ES6类失去了你可能习惯使用es5 react.createClass的自动绑定.当使用ES6作为反应组分时,您必须更加意识到您的绑定.

另一种选择是在构造函数中绑定方法,如下所示:

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

    this.onPress = this.onPress.bind(this)
  }
Run Code Online (Sandbox Code Playgroud)

或者您甚至可以使用胖箭头es6语法函数来维护与您正在创建的组件的"this"绑定:

<Button text={'Sign in'} onPress={() => this.onPress()} />
Run Code Online (Sandbox Code Playgroud)

更新:

要再次更新,如果您的环境支持某些ES7功能(我相信本机构建的反应原理react-native initcreate-react-native-appshoudl),您可以使用此表示法自动绑定使用该this关键字的类方法.

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

代替

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

最好的选择是使用ES7功能(如果可用)或在构造函数中绑定.出于性能原因,使用匿名函数onPress={() => this.onPress()}onPress={this.onPress.bind(this)}直接使用匿名函数Button是不太有利的.