React Native-函数似乎没有被调用

时间:2019-03-19 10:53:33

标签: react-native

我有一个包含2张图片的简单应用。当我单击image1时,我想在控制台上显示问候。 但是我的功能在控制台中什么也没写。 我没有使用函数,而是在第二张图片中直接调用了console.log,它可以正常工作。

您知道我的功能出了什么问题吗? (我也使用了makeALogHello.bind(this),但它没有改变行为。)

export default class App extends React.Component {
  constructor(){
      super();
  }

  makeALogHello(){
    console.log("hello");
  }

  render() {
    return (
      <View>
          <TouchableOpacity style ={{flex:1}}
                            onPress={() => {this.makeALogHello} }>
              <Image  style ={styles.container}
                      resizeMode="contain"
                      source={require("./images/image1.png")}/>
              <Text>ImageNb1</Text>
          </TouchableOpacity>
          <TouchableOpacity style ={{flex:1}}
                            onPress={() => {console.log("hi")} }>
              <Image  style ={styles.container}
                      resizeMode="contain"
                      source={require("./images/image2.png")}/>
              <Text>ImageNb2</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

您需要在箭头函数中调用该函数:

onPress={() => {this.makeALogHello()} }

或者直接将引用传递给函数,而无需将其包装:

onPress={this.makeALogHello}
相关问题