小编典典

在本机的onPress事件期间this.state是未定义的

reactjs

您好,我是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);

  }

}

当我填写此表单并按登录时,我收到以下错误消息:“无法读取未定义的属性’电子邮件’”。感谢您的帮助!


阅读 255

收藏
2020-07-22

共1个答案

小编典典

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

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

ES6类会丢失您可能已经习惯使用es5 react.createClass的自动绑定。使用ES6作为React组件时,您必须更加注意绑定。

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

  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是从shoudl react-native initcreate- react-native-appshoudl 构建的),则可以使用此表示法自动绑定使用该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功能(如果可用)或绑定到构造函数中。由于性能原因,使用匿名函数onPress={() => this.onPress()}
onPress={this.onPress.bind(this)}直接在您的匿名函数上Button使用效果不佳。

2020-07-22