如何在反应中从父级调用子组件函数
问题描述:
如何在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 (
)
}
}