Chrome中的React dev tool显示dom结构是这样的(也符合我的代码):
可chrome中实际显示出来的效果却是这样的:
可以看到,ProductCategoryRow
跑到了SearchBar
和ProductTable
的中间(图中圈出来的部分)。
附上代码:
var data = [
{category: "Sporting Goods", price: "$49.99", stocked: true, name: "Football"},
{category: "Sporting Goods", price: "$9.99", stocked: true, name: "Baseball"},
{category: "Sporting Goods", price: "$29.99", stocked: false, name: "Basketball"},
{category: "Electronics", price: "$99.99", stocked: true, name: "iPod Touch"},
{category: "Electronics", price: "$399.99", stocked: false, name: "iPhone 5"},
{category: "Electronics", price: "$199.99", stocked: true, name: "Nexus 7"}
];
var ProductRow = React.createClass({
render(){
return <tr>
<td>{this.props.name}</td>
<td>{this.props.price}</td>
</tr>
},
});
var ProductCategoryRow = React.createClass({
render(){
return <tr>
{this.props.category}
</tr>
},
});
var ProductTable = React.createClass({
render(){
var category = [];
this.props.data.map(function(item){
if(!category.includes(item.category)){
category.push(item.category);
}
});
var row = [];
for (let value of category){
row.push(<ProductCategoryRow category={value} key={value} />);
this.props.data.map(function(item){
if(item.category == value){
row.push(<ProductRow name={item.name} price={item.price} key={item.name}/>);
}
})
}
return <table>
<tbody>
<tr>
<th>Name</th><th>Price</th>
</tr>
{row}
</tbody>
</table>
}
});
var SearchBar = React.createClass({
render(){
return(<form>
<input type="text"placeholder="search"/>
<input type="checkbox"/>
</form>)
}
});
var FilterableProductTable = React.createClass({
render(){
return <div>
<SearchBar />
<ProductTable data={this.props.data}/>
</div>
}
})
ReactDOM.render(<FilterableProductTable data={data}/>
,document.getElementById('content'));
tr
里面要有td
或th
,你直接在tr
里面放文字浏览器肯定不能正常渲染