2016-12-22 34 views
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> 
    ) 
} 

回答

2

我會建議不同的方法。 不要將引用保存到狀態中的孩子,只需在需要時詢問引用。 而且通過使用一個函數作爲參考它是少車。

您是否需要撥打<MyComponent />或撥打root與div的電話號碼爲navigator.pop()? 在下面的示例中,您可以訪問eather div或組件。

// parent 

render() { 
    return <Child ref={(ref) => this.childNode = ref} /> 
} 

someMethod() { 
    // make sure the component is mounted and you have a referece to child 
    if (this.childNode) { 
    // get child root node 
    const childRootNode = this.childNode.getRootNode() 
    // or get the comp node 
    const compNode = this.childNode.getCompNode() 
    } 
} 


/* child */ 
renderContent(setCompRef) { 
    switch(this.props.tab) { 
     case 0: 
      return (
       <MyComponent ref={setCompRef} /> 
      ); 
     case 1: 
      return (
       <MyComponent2 ref={setCompRef} /> 
      ); 
     case 2: 
      return (
       <MyComponent3 ref={setCompRef} /> 
      ); 
    } 
} 

render() { 
    return (
     <div ref={ref => this.rootNode = ref}> 
      {this.renderContent(
       ref => this.compNode = ref // function that sets ref for component 
      )} 
     </div> 
    ) 
} 

// getters for the two refs 
getRootNode() { 
    return this.rootNode 
} 
getCompNode() { 
    return this.compNode 
} 
+0

我想打電話給 bazi

+0

方法ok,比這個應該可以工作: – bogdanpetru