React Native求助:自定义点击函数未执行,绑定this仍无效
问题分析与解决
你的问题其实出在函数调用的语法错误上,我帮你揪出来啦!
看第一个TouchableOpacity的onPress回调:
onPress={() => {this.makeALogHello} }
这里你只是引用了函数本身,并没有执行它!就像你把一个工具拿出来但没按开关,当然不会有输出啦。而第二个按钮里的console.log("hi")是直接执行了函数,所以能正常打印。
另外你提到用bind(this),其实这个场景里根本不需要绑定this——因为你用了箭头函数包裹,箭头函数会自动继承外部的this上下文,所以问题和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>,我也帮你去掉了,避免渲染报错)
额外优化小建议
如果不想用箭头函数包裹,也可以直接把函数引用传进去,不过这时候需要确保this指向正确,比如在构造函数里绑定:
constructor(){ super(); this.makeALogHello = this.makeALogHello.bind(this); } // 然后render里这样写 <TouchableOpacity style={{flex:1}} onPress={this.makeALogHello}>
或者用类字段语法(更简洁):
makeALogHello = () => { console.log("hello"); } // render里直接传 <TouchableOpacity style={{flex:1}} onPress={this.makeALogHello}>
内容的提问来源于stack exchange,提问作者Me_Will
相关产品推荐
相关产品推荐

