反应:渲染 returns createElement

React : Render returns createElement

我刚开始学习 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>
    );
  }
});

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

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

我的问题是,如何在我的 table 中渲染这个 ProductLine?因为如果我这样做:

<tbody>
  React.createElement ProductLine
</tbody>

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

我可能是错的,但是 <ProductLine /> 是你如何在另一个父组件的渲染函数中实例化一个组件,即:

<tbody>
  <ProductLine />
</tbody>

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

来自 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>
    );
  }
});