0
如何從Parent
中調用渲染的Child
組件的方法?基本上我的應用程序使用switch
語句呈現3個選項卡,每個選項卡在根上包含MyComponent
元素。我嘗試訪問使用props.children
,但是當我調用子方法時,它會引發錯誤。反應:在props.children中獲取組件
/* parent */
changeChild(component) {
this.setState({component});
}
callChildMethod() {
this.state.component.childMethod();
}
render() {
return <Child tab={1} changeChild={this.changeChild} />
}
/* child */
componentDidMount() {
this.props.changeChild(this.refs.root.props.children) // pass to parent here
}
renderContent() {
switch(this.props.tab) {
case 0:
return (
<MyComponent />
);
case 1:
return (
<MyComponent />
);
case 2:
return (
<MyComponent />
);
}
}
render() {
return (
<div ref="root">
{this.renderContent()}
</div>
)
}
我想打電話給 –
bazi
方法ok,比這個應該可以工作: – bogdanpetru