我正在努力寻找解决我的问题的方法,但我无法在任何地方找到它。所以我的问题是如何从孩子调用父函数。该函数必须在孩子内部的 onPress={()} 中传递
父类.js
constructor(props) {
super(props);
this.state = { loading: true };
this.state = { active: 'active' };
this.openDrawer = this.openDrawerButtonFunction.bind(this);
this.callParent = this.callParent.bind(this)
}
callParent = () => {
console.log('I am your father') }
子.js
<Avatar
avatarStyle={{ height: 50 }}
onPress={() => { this.onPressAvatar() }}
source={require('../../assets/images/dav-r.jpeg')} />
onPressAvatar = () => {
console.log('press on avatar');
this.props.callParent.bind(this)
}
原文由 PandaMastr 发布,翻译遵循 CC BY-SA 4.0 许可协议
这是一个常见的误解,所以你会得到很好的照顾。
您将使用
Props
来完成对子函数的父函数调用。自然地,孩子 不 知道父母的功能。当您需要在子组件中执行某些操作,并将其冒泡到父函数时,您只需将函数作为 prop 传递即可。
例子
父组件.js
子组件.js
当您运行函数
someFunctionInChildComponent()
时,它将调用Prop
调用functionPropNameHere
然后移动到父组件以在那里调用函数。输入x
placeholder for x
。