错误:未定义不是函数-React Native

mdh*_*mil 4 android react-native

我创建了一个简单的活动,在该活动中,如果您在圆形区域内按,则其中的文本应相应更改。该应用程序运行良好,但是当我在圆形区域内按时,出现错误消息“未定义不是函数(评估'this.setState({pressing:true});')”)。同样,圆形区域内的文本应首先设置,但为空。您可以在此处查看活动。下面还提供了代码:

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);
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

Sur*_*Rao 6

问题在这里:

<TouchableHighlight onPressIn={this._inPress}
onPressOut={this._outPress}  style={styles.toucher}>
Run Code Online (Sandbox Code Playgroud)

您在设置处理程序时未将上下文固定为current this。因此,setState找不到函数时this会有所不同。使用bind

<TouchableHighlight onPressIn={this._inPress.bind(this)}
   onPressOut={this._outPress.bind(this)}  style={styles.toucher}>
Run Code Online (Sandbox Code Playgroud)

或者您也可以使用箭头功能:

 <TouchableHighlight onPressIn={() => this._inPress()}
       onPressOut={() => this._outPress()}  style={styles.toucher}>
Run Code Online (Sandbox Code Playgroud)