In ES6 class components, this is not bound automatically. So when you call a method like this.setState() inside an event or callback, this may be undefined.
Use arrow functions to preserve this context.
import React, { Component } from 'react';
import { View, TextInput, Alert } from 'react-native';
export default class MyApp extends Component {
state = {
zip: ''
};
// Arrow function preserves 'this'
handleTextChange = (event) => {
const zip = event.nativeEvent.text;
this.setState({ zip });
Alert.alert('Zip Updated:', zip);
};
render() {
return (
<View>
<TextInput
placeholder="Enter ZIP"
onChange={this.handleTextChange}
/>
</View>
);
}
}
Work with our skilled React Native developers to accelerate your project and boost its performance.
Hire React Native Developers