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.
jmancherje
source share