2017-06-08 119 views
0

我创建了一个简单的活动,如果你在圆形区域内按下,其中的文本应该相应地改变。该应用程序运行良好,但当我在圆形区域内按下时,出现错误提示“未定义不是函数(评估'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); 

我该如何解决这个问题?

回答

1

问题就在这里:

<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}> 
+0

嘿感谢。这工作! –

+0

很高兴解决:) –

相关问题