2015-10-13 81 views
0

我有一個父組件拉入一個子組件,該子組件拉入另一個子組件。我希望能夠設置那個孩子的孩子組件來自頂級父母。無法弄清楚如何做到這一點。下面是一些代碼來證明什麼,我試圖做的:如何在父組件中的React中的子組件中設置動態組件?

var TopParent = React.createClass({ 
    render: function() { 
     return (
      <div className="topParent"> 
       <Child componentVariable="BottomChild"> 
      </div> 
     ); 
    } 
}); 

var Child = React.createClass({ 
    render: function() { 
     return (
      <div className="child"> 
       <{this.props.componentVariable} /> // this should pull in a component based on what is passed from TopParent 
      </div> 
     ); 
    } 
}); 

var BottomChild = React.createClass({ 
    render: function() { 
     return (
      <div className="bottomChild"> 
       I am the bottom child. I should be able to be swapped out from TopParent. 
      </div> 
     ); 
    } 
}); 

此外,一旦我弄清楚如何做到這一點,我該如何確保孩子需要的BottomChild組件正確的文件?

+1

你爲什麼不使你的父母你的裏面作爲BottomChild你的孩子的孩子?並通過'this.props.children'將它包含在你的孩子中?這樣,您的父母需要知道要呈現哪個BottomChild,但您的中間孩子不一定需要知道。直接的孩子不需要它。 – wintvelt

回答

3

只使用實際引用,而不是字符串;畢竟,當您手動渲染像<Child />這樣的組件時,也是的參考。

var TopParent = React.createClass({ 
    render: function() { 
     return (
      <div className="topParent"> 
       <Child componentVariable={BottomChild} /> 
      </div> 
     ); 
    } 
}); 

var Child = React.createClass({ 
    render: function() { 
     var Component = this.props.componentVariable; // make sure the var is capitalized 
     return (
      <div className="child"> 
       <Component /> 
      </div> 
     ); 
    } 
}); 

var BottomChild = React.createClass({ 
    render: function() { 
     return (
      <div className="bottomChild"> 
       I am the bottom child. I should be able to be swapped out from TopParent. 
      </div> 
     ); 
    } 
}); 

然而,在許多情況下,它是有道理的,以允許組件to completely control the contents of the child

var TopParent = React.createClass({ 
    render: function() { 
     return (
      <div className="topParent"> 
       <Child> 
        <BottomChild /> 
       </Child> 
      </div> 
     ); 
    } 
}); 

var Child = React.createClass({ 
    render: function() { 
     // `this.props.children` is the *contents* of the `Child` component 
     // as specified in the JSX of `TopParent` 
     return (
      <div className="child"> 
       {this.props.children} 
      </div> 
     ); 
    } 
}); 

var BottomChild = React.createClass({ 
    render: function() { 
     return (
      <div className="bottomChild"> 
       I am the bottom child. I should be able to be swapped out from TopParent. 
      </div> 
     ); 
    } 
}); 
相關問題