我是Reactjs的新手,我有一个从我的db加载json的组件,看起来像这样
Array[2]
0: Object
_id: "56cf587fe46adb3b8960afe2"
price: 2000
title: "ps3"
url: "www.google.com"
__proto__: Object
1: Object
_id: "56db2bd434df9046e0643d22"
price: 499
title: "HENRIKSDAL"
url: "http://www.ikea.com/se/sv/catalog/products/S59847817/"
__proto__: Object
length: 2
__proto__: Array[0]
我想要做的是将数据加载到看起来像这样的表
//start of loop
<tr>
<td className="col-sm-8 col-md-6">
<div className="media">
<div className="media-body">
<h4 className="media-heading"><a href="#">Product name</a></h4>
</div>
</div></td>
<td className="col-sm-1 col-md-1" styles="text-align: center">
<input type="number" name="quantity" min="1" max="10" className="form-control"/>
</td>
<td className="col-sm-1 col-md-1 text-center"><strong>500:-</strong></td>
<td className="col-sm-1 col-md-1 text-center"><strong>$14.61</strong></td>
<td className="actions" data-th="">
<button className="btn btn-info btn-sm"><i className="fa fa-refresh"></i></button>
<button className="btn btn-danger btn-sm"><i className="fa fa-trash-o"></i></button>
</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td><h3>Total</h3></td>
<td className="text-right"><h3><strong>$31.53</strong></h3></td>
</tr>
//end of loop
但我不知道如何遍历数组,因此它将为数组中的每个对象创建一个tablerow。有什么建议?
答案 0 :(得分:6)
您可以映射数组并将数据传递到html
{this.state.data.map(( listValue, index ) => {
return (
<tr key={index}>
<td>{listValue.id}</td>
<td>{listValue.title}</td>
<td>{listValue.price}</td>
</tr>
);
})}
答案 1 :(得分:2)
您可以使用map
方法(在Array的原型中提供)
迭代可以像这样简单......
const rows = [
{
_id: "56cf587fe46adb3b8960afe2",
price: 2000,
title: "ps3",
url: "www.google.com",
}, {
_id: "56db2bd434df9046e0643d22",
price: 499,
title: "HENRIKSDAL",
url: "http://www.ikea.com/se/sv/catalog/products/S59847817/",
}
];
var Hello = React.createClass({
renderRow(props) {
return (
<tr>
<td>{ props._id }</td>
<td>{ props.price }</td>
<td>{ props.title }</td>
<td>{ props.url }</td>
</tr>
);
},
render: function() {
return (
<table>
{ this.props.rows.map(this.renderRow) }
</table>
);
}
});
ReactDOM.render(
<Hello rows={rows} />,
document.getElementById('container')
);
答案 2 :(得分:0)
这是@Andreyco答案的扩展,其中定义了单独的模板,但是在我的情况下,我是在地图调用中引用JSX模板(<Row />
const Table = (props) => (
<div>
<p>Your Table</p>
<table>
<tbody>
{props.rows.map((x,i) => <Row key={i} data={x} />) }
</tbody>
</table>
</div>
)
const Row = (props:any) => (
<tr>
<td>{props.data[0]}</td>
<td>{props.data[1]}</td>
<td>{props.data[2]}</td>
</tr>
)
请参见JSFiddle