我创建了一个简单的活动,如果你按下圆形区域,其中的文本应该相应地改变。该应用程序运行良好,但当我按下圆形区域内部时,我收到一条错误消息“未定义不是函数(评估'this.setState({pressed:true});')”。 此外,圆形区域内的文本应该初始设置,但它是空的。 您可以看到活动here。代码也在下面提供:
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);
我该如何解决这个问题?
答案 0 :(得分:6)
问题在于:
<TouchableHighlight onPressIn={this._inPress}
onPressOut={this._outPress} style={styles.toucher}>
您正在设置处理程序而不将上下文修复为当前this
。
因此,当调用函数时setState
未找到,因为this
将不同。使用bind
。
<TouchableHighlight onPressIn={this._inPress.bind(this)}
onPressOut={this._outPress.bind(this)} style={styles.toucher}>
或者您也可以使用箭头功能:
<TouchableHighlight onPressIn={() => this._inPress()}
onPressOut={() => this._outPress()} style={styles.toucher}>
答案 1 :(得分:2)
只需删除node_modules
运行npm install
react-native run-android
对我有用。