[英]How do you call a parent function from a child component (with parameters) in react-native?
[英]How to call a parent function from a child - react-native
我正在努力寻找解决问题的方法,但我无法在任何地方找到它。 所以我的问题是如何给孩子打电话给父母 function。 function 必须在孩子内部的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)
}
这是一种常见的误解,所以你掌握得很好。
您将利用Props
完成向孩子调用父函数。
当然,孩子不知道父母的功能。 当您需要在子Component中执行某些操作并将其冒泡到父函数时,您只需要将该函数作为prop传递。
例
ParentComponent.js
...
doSomething(x){
console.log(x);
}
render(){
return(
<ChildComponent functionPropNameHere={this.doSomething}/>
)
}
ChildComponent.js
someFunctionInChildComponent(){
this.props.functionPropNameHere('placeholder for x');
}
当您运行someFunctionInChildComponent()
函数时,它将调用名为functionPropNameHere
的Prop
,然后移动到父组件以在那里调用该函数。 在此示例中,输入x
将是x
placeholder for x
。
您必须将父函数作为prop传递给子项。 更多信息在这里
在父渲染功能中
parentfunction(info){
alert(info)
}
render(){
return(
//bla bla bla
<Child functionToPass={this.parentfunction}/>
//bla bla bla
)
}
在孩子身上
callparentfunction(){
this.props.functiontoPass('Hello from the child')
}
父类.js
function doSomething(info){
console.log("Parent Function")
}
render(){
return(
<ChildComponent functionPropNameHere={doSomething()}/>
)
}
子.js
function callparentfunction(){
props.functionPropNameHere()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.