如何从本机子React调用父函数

qv7cva1a  于 2022-11-25  发布在  React
关注(0)|答案(4)|浏览(143)

我一直在努力寻找解决问题的方法,但是到处都找不到。所以我的问题是如何从子函数中调用父函数。函数必须在子函数中以**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)

}

lnxxn5zx

lnxxn5zx1#

这是一个常见的误解,所以你在良好的手中。
您将使用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

mwg9r5ms

mwg9r5ms2#

在父呈现函数中

parentfunction(info){
   alert(info)
}

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

"在孩子体内"

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

e0uiprwp3#

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

cs7cruho

cs7cruho4#

Parent.js

function doSomething(info){
   console.log("Parent Function")
}

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

Child.js

function callparentfunction(){
props.functionPropNameHere()
}

相关问题