简体   繁体   English

从父功能组件调用 class 子组件方法

[英]Call class child component method from parent functional component

i have two components:我有两个组件:

Parent.js父.js

import React from 'react
import Child from './Child'

function Parent() {

return (
    <div> 
         <Child />
         <button onClick={invoke child method onClick} > Button </button>
    </div>
 )
}

export default Parent

Child.js Child.js

import React from 'react

class Child extends Component {

getAlert() {
    console.log("called from parent")
}

render() {
    return (
        <div> 
          This is from child
        </div>
    )
  }
}

export default Child

Now, I want to call getAlert() method from parent component we can say i want to call a child method from parent.现在,我想从父组件调用getAlert()方法,我们可以说我想从父组件调用子方法。 Please notice Parent is functional and child is class.请注意父母是功能性的,孩子是 class。

Here is how you can do it.这是你如何做到的。

import React from 'react'
import Child from './Child'

function Parent() {
  const handleAlert=(paramfn?:any)=>{
     if(paramfn){
         paramfn();
     }
  }

return (
    <div> 
         <Child onAlert={handleAlert} />
         <button onClick={invoke child method onClick} > Button </button>
    </div>
 )
}

export default Parent

/*********Child**********/

import React from 'react'

class Child extends Component {

getAlert() {
    console.log("called from parent")
}

render() {
    return (
        <div onClik ={()=>this.props.onAlert(getAlert);}> 
          This is from child
        </div>
    )
  }
}

export default Child

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM