本文介绍了如何在反应中从父级调用子组件函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在react中从Parent调用子组件函数
How to call child component function from Parent in react
点击按钮需要从parentComponent调用子函数needToBeCalled()
on click of button need to call child function needToBeCalled() from parentComponent
请参考下面的片段
class Parent {
render(){
return(
<button onClick={() => }>Click</button>
<Child />
)
}
}
class Child {
function needToBeCalled() {
}
render(){
return (
)
}
}
推荐答案
这是 React 中的反模式,但你可以使用 ref 来做类似的事情
It's antipattern in React, but you can use ref to do something like so
class Parent {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render(){
return(
<button onClick={this.myRef.current}>Click</button>
<Child myRef={this.myRef}/>
)
}
}
class Child {
componentDidMount(){
function needToBeCalled() {
}
this.props.myRef.current = needToBeCalled
}
render(){
return (
)
}
}
这篇关于如何在反应中从父级调用子组件函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!