React:Render返回createElement

时间:2015-07-13 15:15:35

标签: javascript ruby-on-rails reactjs react-jsx

我刚开始学习React,我正在使用Rails后端。

在我看来,我有:

<%= react_component 'Products', { data: @products } %>

使用此静态代码可以正常工作:

var Products = React.createClass({
  getInitialState: function () {
    return {products: this.props.data};
  },

  getDefaultProps: function() {
    return {products: []};
  },

  render: function () {
    return (
      <div className="products">

        <h2 className="title">List of products</h2>

        <table className="table table-bordered">
          <thead>
            <tr>
              <th>Name</th>
              <th>Company</th>
              <th>RRP</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>AAA</td>
              <td>BBB</td>
              <td>CCC</td>
            </tr>
          </tbody>
        </table>

      </div>
    );
  }
});

我的桌子显示得很好。 下一步是获得相同的结果,但每行代表一个新产品的元素。所以我开始在同一个文件中创建一个新的React类:

var ProductLine = React.createClass({
  render: function () {
    return (
      <tr>
        <td>AAA</td>
        <td>BBB</td>
        <td>CCC</td>
      </tr>
    );
  }
});

我的问题是,如何在表格中呈现此ProductLine?因为如果我这样做:

<tbody>
  React.createElement ProductLine
</tbody>

该行被视为纯文本而未呈现...

2 个答案:

答案 0 :(得分:1)

实际上我在发布这个问题之后就找到了解决方案。

来自Pete Hunt的

This post called Thinking in React非常有用,特别是对于React新手。此外,这个例子与我的情况几乎相同......

var ProductRow = React.createClass({
  render: function () {
    return (
      <tr>
        <td>{this.props.product.name}</td>
        <td>{this.props.product.company_id}</td>
        <td>{this.props.product.price}</td>
      </tr>
    );
  }
});


var ProductTable = React.createClass({
  render: function () {
    var rows = [];

    this.props.data.forEach(function(product) {
      rows.push(<ProductRow product={product} key={product.id} />);
    });

    return (
      <div className="products">

        <h2 className="title">List of products</h2>

        <table className="table table-bordered">
          <thead>
            <tr>
              <th>Name</th>
              <th>Company</th>
              <th>RRP</th>
            </tr>
          </thead>
          <tbody>
            {rows}
          </tbody>
        </table>

      </div>
    );
  }
});

答案 1 :(得分:0)

我错了,<ProductLine /&gt;是如何在另一个父组件的render函数中实例化一个组件,即:。

<tbody>
  <ProductLine />
</tbody>