2015-02-05 58 views
0

使用React 0.12.2並給定佈局組件,例如,一個托盤:帶動態子組件的ReactJS佈局組件

<div className="tray"> 
    <div className="tray__item tray__item--left" data-width="260px"> 
     Load a component in the left tray 
    </div> 
    <div className="tray__item tray__item--center"> 
     Load a component in the center tray 
    </div> 
    <div className="tray__item tray__item--right" data-width="100%"> 
     Load a component in the right tray 
    </div> 
</div> 

我想能夠在每個內容中插入任意組件,並將它們作爲參數傳遞給此組件。

也許是這樣的:

<Tray left={Component1} center={Component2} right={Component3}/> 

我也想知道如何通過組件例如一個未知量:

<Carousel items={Component1,Component2,Component3,Component4}/> 

只要是明確的 - 這些容器組件是「啞巴」 - 他們只關心滑動內容 - 你應該能夠傳遞你想要的任何內容(組件)。

我該怎麼做,然後渲染它們?謝謝。

+1

您可以通過數組作爲這樣的性質: '項目= {[的Component1,COMPONENT2,Component3,Component4]}' – SimpleJ 2015-02-05 21:59:39

+0

感謝@SimpleJ - 很明顯! – 2015-02-05 22:04:59

回答

2

傳遞一個組件在托盤的渲染方法,你可以在你的盤住組件做

render: function() { 
    return (
     <div className="tray"> 
     {this.props.children} 
     </div> 
    ); 
    } 

然後,你可以做

<Tray> 
    <TrayItem position="left"/> 
    <TrayItem position="center"/> 
    <TrayItem position="right"/> 
</Tray> 

你應該能夠繼續嵌套​​這種模式,即

<Tray> 
    <TrayItem position="left"> 
    <SomeComponent/> 
    </TrayItem> 

    <TrayItem position="center"> 
    <div> 
     <AnotherComponent/> 
    </div> 
    </TrayItem> 

    <TrayItem position="right"/> 
</Tray> 

在這種情況下,TrayItem的渲染也應該包括de {this.props.children}

一般原理是,只要容器組件的渲染包含{this.props.children},就可以將任意組件放入其他組件中。

+0

謝謝 - 以及如何將組件傳遞給TrayItem? – 2015-02-05 21:50:32

+0

我編輯了我的答案來覆蓋這個。 – 2015-02-05 22:23:07

-1

您應該創建一個在其渲染函數中具有多個子組件的容器組件。你永遠不希望在爲道具

+0

我不知道這些子組件是什麼 - 組件是「啞」 – 2015-02-05 21:36:16

+0

你怎麼知道它們是什麼?你可以舉一個jsfiddle的例子嗎? – zackify 2015-02-05 21:36:53

+0

如果我製作一個可重複使用的托盤組件,它只關心它是否滑動內容,它並不關心內容是什麼 - 我希望能夠在多個位置使用該組件,並告訴它組件將進入內部它在哪裏使用 – 2015-02-05 21:38:08

2

感謝Adam Stone + SimpleJ的回答。

var Tray = React.createClass({ 
    render: function() { 
     return (
      <div className="tray"> 
       {this.props.children} 
      </div> 
     ); 
    } 
}); 

var TrayItem = React.createClass({ 
    render: function() { 
     return (
      <div className="tray__item"> 
       {this.props.children} 
      </div> 
     ); 
    } 
}); 

<Tray> 
    <TrayItem> 
     <ComponentA/> 
     <ComponentAB/> 
    </TrayItem> 
    <TrayItem> 
     <ComponentB/> 
    </TrayItem> 
    <TrayItem> 
     <ComponentC/> 
    </TrayItem> 
</Tray>