This.state undefined during onPress event in native reaction

Hi, I know that in real native, my code is:

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

When I fill out this form and click on the login button, I get this error message: "Unable to read the" email "property from undefined". Thanks for the help!

+8
javascript reactjs
source share
1 answer

This is a required issue. The easiest solution is to change the JSX for the button tag as follows:

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

ES6 classes lose auto-communication, which you may be used to with es5 react.createClass. You need to be more aware of your bindings when using ES6 to respond to components.

Another option is to bind the method in your constructor as follows:

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

Or you can even use the syntax function fat arrow es6 to support the binding of 'this' to the component you are creating:

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

UPDATE:

To refresh this again, if your environment supports some ES7 features (which I assume are built into the react-native init variable or create-react-native-app shoudl do), you can use this notation to automatically bind class methods that use this .

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

instead

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

The best options are to use the ES7 function, if available, or for binding in your constructor. Using the anonymous function onPress={() => this.onPress()} or onPress={this.onPress.bind(this)} directly on your Button much less performance-friendly.

+16
source share

All Articles