i have two components:
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
Now, I want to call getAlert() method from parent component we can say i want to call a child method from parent. Please notice Parent is functional and child is 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.