2016-10-15 4 views
2

나는 이것을 체크했다 linkReact Router의 자식에게 어떻게 소품을 전달할 수 있습니까?

지금까지 나는 handler 부분을 이해할 수 없다. 그래서 나는 좀 더 간단한 예제를 원했던 것일까?

class appTemplate extends React.Component { 
    render() { 
     return (
      <div> 
       <Header lang={this.props.route.path}/> 
       {this.props.children} 
       <Footer lang={this.props.route.path}/> 
      </div> 
     ); 
    } 
} 

는 내가하고 싶은 것은 this.props.children 내 아이 컴퍼넌트에 소품 this.props.route.path을 전달할 수 있습니다 :

여기 내 주요 부모 구성 요소입니다.

나는 이미 지난 몇 개월 동안 React를 만져 왔지만 모든 용어에 대해 완전히 익숙하지 않습니다.

적절한 설명이있는 예제는 크게 감사하겠습니다. 감사.

+0

을 사용하고, 최신 문서를 체크 아웃 .... 연결 래퍼를 사용하는 것보다 redux를 사용하는 경우이 위치와 경로에 대한 액세스를 제공 할 것입니다. – abhirathore2006

답변

5

적절한 방법 것은 예를 꽤 오래된 것을 React.Children.map()

class appTemplate extends React.Component { 
    render() { 
     return (
      <div> 
       <Header lang={this.props.route.path}/> 
       {React.Children.map(
         this.props.children, 
         child => React.cloneElement(child, 
            { 
             customProp: "Here is your prop", 
             path: this.props.route.path 
            }) 
       )} 
       <Footer lang={this.props.route.path}/> 
      </div> 
     ); 
    } 
} 
+0

덕분에 –

+0

저의 작품도 감사합니다. – rorymorris89

0

React에는 cloneElement 함수가 있습니다.

class appTemplate extends React.Component { 
    render() { 
     let children = null; 
     if (this.props.children) { 
      children = React.cloneElement(this.props.children, { 
      path: this.props.route.path 
      }) 
     } 
     return (
      <div> 
       <Header lang={this.props.route.path}/> 
       {children} 
       <Footer lang={this.props.route.path}/> 
      </div> 
     ); 
    } 
} 

것은 그런 다음 자식 요소 내에서 this.props.path를 사용하여 경로에 액세스 할 수 있지만, (내가 기억하는 것과) 안 : 아이디어는 소품의 일환으로 경로에 전달, 아이들 개체를 복제하는 것입니다 자식 안에 중첩 된 요소 내에서.

당신은 복제 여기에 값을 전달하는 방법에 대해 자세히 읽을 수 있습니다 : 그것을 달성하기 https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement

관련 문제