首页 > 解决方案 > 如何从孩子调用父函数 - 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)

}

标签: javascriptreactjsreact-nativereact-native-androidreact-native-ios

解决方案


这是一个常见的误解,所以你掌握得很好。

您将利用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,然后移动到父组件以在那里调用该函数。输入xplaceholder for x在此示例中。


推荐阅读