2016-12-22 6 views
0

Parent에서 렌더링 된 Child 구성 요소의 메소드를 어떻게 호출 할 수 있습니까? 기본적으로 내 응용 프로그램은 switch 문을 사용하여 각각 루트에 MyComponent 요소를 포함하는 3 개의 탭을 렌더링합니다. props.children을 사용하여 액세스를 시도했지만 자식 메서드를 호출하면 오류가 발생합니다.React : 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

나는 다른 방법을 제안합니다. 주에서 아동에게 보증인을 저장하지 말고, 필요할 때 참조를 요청하십시오. 또한 ref로 함수를 사용하면 덜 버그가 있습니다.

<MyComponent /> 또는 ref root으로 div에 navigator.pop()을 호출해야합니까? 다음 예에서 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

의 메소드를 호출하고 싶습니다. 정상적으로 작동합니다. – bogdanpetru

관련 문제