簡體   English   中英

從父功能組件調用 class 子組件方法

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

我有兩個組件:

父.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()方法,我們可以說我想從父組件調用子方法。 請注意父母是功能性的,孩子是 class。

這是你如何做到的。

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