【问题标题】:ReactJS layout component with dynamic child components带有动态子组件的 ReactJS 布局组件
【发布时间】:2015-04-05 22:15:08
【问题描述】:

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

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

我怎样才能做到这一点然后渲染它们?谢谢。

【问题讨论】:

  • 您可以将数组作为属性传递,如下所示:items={[Component1,Component2,Component3,Component4]}
  • 感谢@SimpleJ - 很明显!

标签: javascript layout dynamic components reactjs


【解决方案1】:

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

【讨论】:

  • 我不知道这些子组件是什么——组件是“哑”
  • 你怎么不知道它们是什么?你能举个关于 jsfiddle 的例子吗?
  • 如果我正在制作一个可重复使用的托盘组件,它唯一关心的是它会滑动内容,它并不关心内容是什么 - 我希望能够在多个地方使用该组件并且告诉它哪些组件将进入它的使用位置
  • 您应该有一组数据传入其中,而不是完整的组件。我知道你要去哪里,但不完全。你到底在做什么?
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-08
      • 2013-04-06
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 2014-12-16
      • 2018-10-05
      相关资源
      最近更新 更多