[英]How to pass value from a child functional component to parent class component?
[英]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.