我不明白为什么第一个代码示例在按下按钮时呈现正常,而另一个示例当我将其放入基金会时,它无法识别该功能。
//This executes as expected
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.handlePress.bind(this)}>
<Text style={{paddingTop: 10, paddingLeft: 10, color:
'#FF0000'}}>Prova</Text>
</TouchableOpacity>
</View>
-------------------------------------------------------------------
//Here it can't recognise the function
func1(){
this.handlePress.bind(this);
};
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.func1()}>
<Text style={{paddingTop: 10, paddingLeft: 10, color:
'#FF0000'}}>Prova</Text>
</TouchableOpacity>
</View>
将函数转换为箭头函数,忘记绑定...箭头函数自动绑定到其父级...
handlePress = () => {};
-
<TouchableOpacity onPress={this.handlePress}>
你不需要绑定 this.handlePress.bind(this(; 在 func1 中。
就叫它
func1(){
this.handlePress()
}
使用 this.handlePress.bind(this(,您不会调用该函数,而只是将函数 bounfd 返回给 'this'