[英]pass a function to child component react native
我尝试将 onChangeText() 传递给 react native 中的子组件,它起作用了:
onChangText(value){
console.log(value)
}
render() {
return (
<View style={{flex:1}}>
<Ui
onChangeText={this.onChangText()}
/>
</View>
)
}
但是当我像下面这样调用其他函数(在父函数中)时:
loger(value){
console.log(value)
}
onChangText(value){
this.loger(value)
}
render() {
return (
<View style={{flex:1}}>
<Ui
onChangeText={this.onChangText()}
/>
</View>
)
}
我收到错误:this.loger 不是函数
你需要注意的两件事
首先,在将函数传递给 child 时,您不需要调用它,只需像传递引用一样
<Ui
onChangeText={this.onChangText}
/>
其次,每当您需要在被调用的函数中使用this
关键字时,您应该将函数绑定到正确的上下文。 在您的情况下,您需要将其绑定到父类的上下文,因此您可以为此使用箭头函数
onChangText = (value) => {
this.loger(value)
}
我通过在箭头函数的主体中传递我的函数来解决这个问题,如下所示:
loger(value){
console.log(value)
}
onChangeText(value){
this.loger(value)
}
render() {
return (
<View style={{flex:1}}>
<Ui
onChangeText={(value)=> this.onChangeText(value)}
/>
</View>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.