问题
I am trying to build a table dynamically generated from output array of PHP script. I get the below output after componentWillMount is executed. But I am trying to use this data ( first 4 rows are one row ) and build a table. But i am unable to get how to use this array data and convert it to table dynamically. Any inputs are highly appreciated.
2016-08-24 20:24:06
2016-08-24 20:24:06
test01
20
2016-08-19 08:14:25
2016-08-19 08:14:25
test02
10
componentWillMount: function () {
$.ajax({
type: "GET",
crossDomain: true,
url: "http://localhost:8080/myscript.php",
success: function(data){
alert(data);
this.setState({testRows: data});
}.bind(this),
error:function(data)
{
alert("Data sending failed");
}
});
},
return(
<tbody>
{this.state.testRows.map(function(row, i) {
return (
<tr key={i}>
{row.map(function(col, j) {
return <td key={j}>{col}</td>;
})}
</tr>
);
})}
</tbody>
)
回答1:
What I do is that i create a 2-dimensional array which i pass to the List component. If you know that every group of 4 in the array you get from the php script is a row then you just use a for loop like this.(phpResponse is the response from the php script)
var tableData = [];
var tableRow = [];
for(var x = 1; x <= phpResponse.length; x++) {
tableRow.push(phpResponse[x]);
if (x % 4 == 0) {
tableData.push(tableRow);
tableRow = [];
}
}
And then you use tableData like this
return(
<tbody>
{tableData.map((row, index) => {
return (
<tr key={"row_" + index}>
{row.map((cell, index) => {
return (
<td key={"cell_" + index}>{cell}</td>
);
})}
</tr>
);
})}
</tbody>
);
来源:https://stackoverflow.com/questions/39137647/build-a-dynamic-table-using-array-data-generated-from-php-in-jsx-react