javascript - 如何从孩子调用父函数 - react-native
问题描述
我正在努力寻找解决问题的方法,但我在任何地方都找不到。所以我的问题是如何从 child 调用父函数。该函数必须在子级内部的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') }
Child.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)
}
解决方案
这是一个常见的误解,所以你掌握得很好。
您将利用Props
它来完成对孩子的调用父函数。
自然,孩子不知道父母的功能。当您需要在子组件中做某事并将其冒泡到父函数时,您只需将该函数作为道具传递。
例子
父组件.js
...
doSomething(x){
console.log(x);
}
render(){
return(
<ChildComponent functionPropNameHere={this.doSomething}/>
)
}
ChildComponent.js
someFunctionInChildComponent(){
this.props.functionPropNameHere('placeholder for x');
}
当您运行该函数someFunctionInChildComponent()
时,它会调用被Prop
调用的functionPropNameHere
,然后移动到父组件以在那里调用该函数。输入x
将placeholder for x
在此示例中。
推荐阅读
- c# - FileSystemWatcher 无法检测到 1 个文件的变化(添加新文件),只能检测到至少 2 个文件
- javascript - 为什么 JavaScript 不在这里填充文本框?
- java - 无法在 ButterKnife 中使用 findById
- javascript - 如何在传单中加载 geoJSON?
- mysql - 将秒转换为 MySQL 中秒大于 24 小时的时间
- django - 包含匹配的 Django ArrayField 过滤
- excel - 无法单击网络表单中的按钮
- javascript - 如何在 vuetify 数据表中显示数据
- c++ - 如何在 arduino 或 Raspberrypi 上制作 600MHz 循环?
- node.js - Angular未登录用户详细信息