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

时间:2021-01-06 10:43:01

标签: javascript reactjs

我有两个组件:

Parent.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

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

现在,我想从父组件调用 getAlert() 方法,我们可以说我想从父组件调用子方法。 请注意父级是函数式的,子级是类。

1 个答案:

答案 0 :(得分:0)

这是您的方法。

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