在 JSX/React 中使用 PHP 生成的数组数据构建动态表

2023-12-05

我正在尝试构建一个从 PHP 脚本的输出数组动态生成的表。执行 componentWillMount 后得到以下输出。但我正在尝试使用这些数据(前 4 行是一行)并构建一个表。但我无法了解如何使用此数组数据并将其动态转换为表。任何意见都将受到高度赞赏。

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 脚本的响应)

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

return(
    <tbody>
         {tableData.map((row, index) => {
             return (
                 <tr key={"row_" + index}>
                     {row.map((cell, index) => {
                         return (
                             <td key={"cell_" + index}>{cell}</td>
                         );
                     })}
                 </tr>
             );
         })}
    </tbody>
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 JSX/React 中使用 PHP 生成的数组数据构建动态表 的相关文章

随机推荐