React.js:将一个组件包装到另一个组件中 [英] React.js: Wrapping one component into another

查看:704
本文介绍了React.js:将一个组件包装到另一个组件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多模板语言都有slots或yield语句,允许进行某种控制反转,将一个模板包装在另一个模板中。

Many template languages have "slots" or "yield" statements, that allow to do some sort of inversion of control to wrap one template inside of another.

Angular已转换选项

Rails有 yield语句。如果React.js有yield语句,它将如下所示:

Rails has yield statement. If React.js had yield statement, it would look like this:

var Wrapper = React.createClass({
  render: function() {
    return (
      <div className="wrapper">
        before
          <yield/>
        after
      </div>
    );
  }
});

var Main = React.createClass({
  render: function() {
    return (
      <Wrapper><h1>content</h1></Wrapper>
    );
  }
});

所需产出:

<div class="wrapper">
  before
    <h1>content</h1>
  after
</div>

唉,React.js没有< yield /> ; 。如何定义Wrapper组件以实现相同的输出?

Alas, React.js doesn’t have a <yield/>. How do I define Wrapper component to achieve the same output?

推荐答案

尝试:

var Wrapper = React.createClass({
  render: function() {
    return (
      <div className="wrapper">
        before
          {this.props.children}
        after
      </div>
    );
  }
});

参见多个组件:儿童儿童类型道具在文档中获取更多信息。

See Multiple Components: Children and Type of the Children props in the docs for more info.

这篇关于React.js:将一个组件包装到另一个组件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆