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

新手上路,请多包涵

我正在努力寻找解决我的问题的方法,但我无法在任何地方找到它。所以我的问题是如何从孩子调用父函数。该函数必须在孩子内部的 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)

}

原文由 PandaMastr 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 274
2 个回答

这是一个常见的误解,所以你会得到很好的照顾。

您将使用 Props 来完成对子函数的父函数调用。

自然地,孩子 知道父母的功能。当您需要在子组件中执行某些操作,并将其冒泡到父函数时,您只需将函数作为 prop 传递即可。

例子

父组件.js

 ...

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

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

子组件.js

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

当您运行函数 someFunctionInChildComponent() 时,它将调用 Prop 调用 functionPropNameHere 然后移动到父组件以在那里调用函数。输入 x placeholder for x

原文由 Nikush 发布,翻译遵循 CC BY-SA 4.0 许可协议

在父渲染函数中

parentfunction(info){
   alert(info)
}

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

在孩子

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

原文由 ValdaXD 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题