I created a simple activity where in if you press inside the circular area, the text in it should change accordingly. The app runs well but when I press inside the circular area, I get an error saying "undefined is not a function ( evaluating 'this.setState( {pressing: true});' ) ". Also, the text inside the circular area should be initially set but it is empty. You can see the activity here. The code is also provided below:
import React, { Component } from "react";
import {
StyleSheet,
View,
AppRegistry,
Text,
TouchableHighlight
} from "react-native";
class dhrumil extends Component {
constructor(props) {
super(props);
this.state = { pressing: false };
}
_inPress() {
this.setState({ pressing: true });
}
_outPress() {
this.setState({ pressing: false });
}
render() {
return (
<View style={styles.mainContainer}>
<TouchableHighlight
onPressIn={this._inPress}
onPressOut={this._outPress}
style={styles.toucher}
>
<View style={styles.smallContainer}>
<Text style={styles.texter}>
{this.state.pressing ? "EEK" : "PUSH ME"}
</Text>
</View>
</TouchableHighlight>
</View>
);
}
}
var styles = StyleSheet.create({
mainContainer: {
flex: 1,
backgroundColor: "white",
justifyContent: "center",
margin: 10,
alignItems: "center"
},
toucher: {
borderRadius: 100
},
smallContainer: {
backgroundColor: "#ff0000",
width: 200,
height: 200,
borderRadius: 100
},
texter: {
color: "white",
fontSize: 10,
fontWeight: "bold"
}
});
AppRegistry.registerComponent("dhrumil", () => dhrumil);
How can I solve this?
The issue is here:
<TouchableHighlight onPressIn={this._inPress}
onPressOut={this._outPress} style={styles.toucher}>
You are setting handlers without fixing the context as the current this
.
So when the functions are called setState
is not found as this
will be different. Use bind
.
<TouchableHighlight onPressIn={this._inPress.bind(this)}
onPressOut={this._outPress.bind(this)} style={styles.toucher}>
Or you can also use arrow function:
<TouchableHighlight onPressIn={() => this._inPress()}
onPressOut={() => this._outPress()} style={styles.toucher}>
simply delete node_modules
run npm install
react-native run-android
It's worked for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With