How to call a parent function from a child - react-native

问题: I'm struggling to find a solution to my problem , but i cannot find it anywhere . So my question is how to call a parent function from a child . The function has to be pass...

问题:

I'm struggling to find a solution to my problem , but i cannot find it anywhere . So my question is how to call a parent function from a child . The function has to be passed in a onPress={()} inside the child

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)

}


回答1:

This is a common mis-understanding, so you're in good hands.

You're going to utilize Props to accomplish calling a parent function to a child.

Naturally, the child knows not of the parent's functions. When you need to do something in the child Component, and bubble it up to the parent function, you just need to pass the function as a prop.

Example

ParentComponent.js

...

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

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

ChildComponent.js

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

When you run the function someFunctionInChildComponent(), it will call the Prop called functionPropNameHere which then moves to the parent component to call the function there. The input x will be placeholder for x in this example.


回答2:

You have to pass the parent function as a prop to the child. More info here


回答3:

In the parent render function

parentfunction(info){
   alert(info)
}


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

In the child

callparentfunction(){
this.props.functiontoPass('Hello from the child')
}
  • 发表于 2019-01-10 20:26
  • 阅读 ( 205 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除