我已经实现了从父组件到子组件的回调,并成功地从子组件调用它,如 answer 中所述.在我的回调中,我需要父级的 props
,navigate
prop。但是回调中的this.props
返回undefined
。我如何获得 Prop 对象?我不想将导航 Prop 传递给 child 。
回调:
_onSeperatorPress(item){
console.log(item);
console.log(this);
this.navigation.navigate("main");
}
家长调用 child :
<HorizontalList
data={genresData}
keyExtractor={(item, index) => item.description}
onPress={this._onSeperatorPress} />
子调用回调:
<TouchableHighlight
onPress={() => this.props.onPress(item)}
onShowUnderlay={separators.highlight}
onHideUnderlay={separators.unhighlight}>
</TouchableHighlight>
最佳答案
您有约束力问题。您需要绑定(bind)函数才能访问函数内的状态或 Prop 。
ES5: 普通函数,你需要在构造函数中手动绑定(bind)它
this.handleFunction = this.handleFunction.bind(this);
handleFunction(){
console.log(this.props); // props are available
}
ES6:箭头函数 - 自动绑定(bind),你可以远离范围相关的问题
handleFunction = () = {
console.log(this.props); // props are available
}
关于javascript - 在发送给子组件的回调中找不到父项的 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52181500/