【问题标题】:Nesting react components dynamically , adding custom JSX on the fly inside the component?动态嵌套反应组件,在组件内动态添加自定义 JSX?
【发布时间】:2016-04-19 07:21:09
【问题描述】:
<div className="header">
   <Card>
      <div className="logo">
          <Logo />
      </div>
      <div className="timer">
          <Timer />
      </div>
   </Card>
</div>

我想实现这样的目标。我已经创建了一个组件卡,现在我希望这个组件应该包含任何随机 JSX 以及其他组件。

我已经有了使用 React.Children 方法嵌套 React Children 的方法,但是我无法找到,如何处理组件内部的附加 JSX。

【问题讨论】:

  • 只是{this.props.children}

标签: reactjs


【解决方案1】:

您可以简单地使用this.props.children

要处理这个特定的数据结构,您可以使用React.Children utilities

例如,如果您只想为 Card 中的每个子组件添加一个包装 div,您可以编写:

const Card = React.createClass({
    render: function() {
        const wrappedChildren = React.Children.map(
            this.props.children,
            function(oneChild) {
                return (
                    <div className="wrappingDiv">
                        {oneChild}
                    </div>
                );
            },
        );
        return (
            <div className="cardContainer">
                {wrappedChildren}
            </div>
        );
    },
});

// then:
<Card>
   <Logo />
   <Timer />
</Card>

【讨论】:

  • 包装 div 可能包含基于某些条件的不同类,我想将逻辑与卡片组件分离。
  • 然后你可以忘记 Card 组件中的 WrappedChildren 东西,只需在 container-div 中用 this.props.children 替换它。您可以在问题中编写组件时渲染组件。那你还有问题吗?
  • 很抱歉,我不明白您的问题。您能否通过编辑您的问题以适当的代码示例来解释它?
【解决方案2】:

做这样的事情,

var ParentComponent = React.createClass({
    render : function(){
        var el = (<component_you_want_to_nest />);
        return(
            <ComponentCardComponent nestComp={el} />
        )
    }
});

var ComponentCardComponent = React.createClass({
render : function(){
    <div>
        {this.props.nestComp}
    </div>
}

});

【讨论】:

  • 我认为你可以做到children={el}this.props.children
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-28
  • 2017-12-14
  • 1970-01-01
  • 1970-01-01
  • 2020-04-01
  • 2017-10-10
相关资源
最近更新 更多