具有动态子组件的 ReactJS 布局组件

ReactJS layout component with dynamic child components

使用 React 0.12.2 并给定布局组件,例如一个托盘:

<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}/>

明确一点 - 这些容器组件是 "dumb" - 它们只关心滑动内容 - 你应该能够将你想要的任何内容(组件)传递给它们。

我该怎么做然后渲染它们?谢谢

您应该只创建一个在其渲染函数中具有多个子组件的容器组件。您永远不想将组件作为道具传入

在Tray的render方法中可以做

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 的呈现还应包括 {this.props.children}

总的原则是,只要容器组件的渲染包含 {this.props.children},您就可以将任意组件放入其他组件中。

感谢 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>