如何从子级调用父级函数-react-native

时间:2019-01-09 14:54:44

标签: javascript reactjs react-native react-native-android react-native-ios

我正在努力寻找解决问题的办法,但我找不到任何地方。所以我的问题是如何从孩子那里调用父函数。该功能必须在子对象内的 onPress = {()} 中传递

Parent.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)

}

3 个答案:

答案 0 :(得分:1)

您必须将父函数作为道具传递给孩子。 More info here

答案 1 :(得分:1)

在父渲染功能中

parentfunction(info){
   alert(info)
}


render(){
      return(
       //bla bla bla
       <Child functionToPass={this.parentfunction}/>
       //bla bla bla
      )
    }

在孩子中

callparentfunction(){
this.props.functiontoPass('Hello from the child')
}

答案 2 :(得分:1)

这是一个常见的误解,因此您处于良好状态。

您将利用Props完成对孩子的父函数调用。

自然,孩子对父母的功能了解不强。当您需要在子组件中执行某些操作并将其冒泡给父函数时,只需将函数作为道具传递即可。

示例

ParentComponent.js

...

doSomething(x){
   console.log(x);
}

render(){
   return(
      <ChildComponent functionPropNameHere={this.doSomething}/>
   )
}

ChildComponent.js

someFunctionInChildComponent(){
   this.props.functionPropNameHere('placeholder for x');
}

运行函数someFunctionInChildComponent()时,它将调用名为Prop的{​​{1}},然后移至父组件以在那里调用该函数。在此示例中,输入functionPropNameHere将是x

相关问题