如何从 child - react-native 调用 parent 函数

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

我正在努力寻找解决我的问题的方法,但我找不到任何地方。所以我的问题是如何从 child 调用 parent 函数。该函数必须在 child

中的 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)

}

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

在父渲染函数中

parentfunction(info){
   alert(info)
}


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

中子

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

这是一个常见的 mis-understanding,所以你得到了很好的帮助。

您将使用 Props 来完成对 child 的 parent 函数的调用。

当然,child 知道 而不是 parent 的功能。当你需要在 child 组件中做一些事情,并将其冒泡到 parent 函数时,你只需要将函数作为 prop 传递。

示例

ParentComponent.js

...

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

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

ChildComponent.js

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

当你 运行 函数 someFunctionInChildComponent() 时,它将调用 Prop 调用 functionPropNameHere 然后移动到 parent 组件来调用函数那里。在此示例中,输入 x 将是 placeholder for x