[英]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>
);
}
});
我的桌子擺放得很好。 下一步是獲得相同的結果,但每行代表一個新產品的元素。 所以我開始在同一文件中創建一個新的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>
該行被視為純文本,不呈現。
實際上,我在發布此問題后才找到解決方案。
皮特·亨特(Pete Hunt) 撰寫的這篇題為《在React中思考》(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>
);
}
});
我可能是錯的,但是<ProductLine
/>是如何在另一個父組件的render函數中實例化一個組件,即:
<tbody>
<ProductLine />
</tbody>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.