在 JSX/React 中使用 PHP 生成的数组数据构建动态表 [英] Build a dynamic table using array data generated from PHP in JSX/React
问题描述
我正在尝试构建一个从 PHP 脚本的输出数组动态生成的表.执行 componentWillMount 后,我得到以下输出.但我正在尝试使用这些数据(前 4 行是一行)并构建一个表.但我无法获得如何使用此数组数据并将其动态转换为表格.任何输入都受到高度赞赏.
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>
)
推荐答案
我所做的是创建一个二维数组,并将其传递给 List 组件.如果您知道从 php 脚本获得的数组中的每组 4 是一行,那么您只需使用这样的 for 循环.(phpResponse 是来自 php 脚本的响应)
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 = [];
}
}
然后你像这样使用 tableData
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>
);
这篇关于在 JSX/React 中使用 PHP 生成的数组数据构建动态表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!