gpt4 book ai didi

javascript - 在react中使用thead和tbody标签循环遍历数组

转载 作者:行者123 更新时间:2023-11-28 04:19:32 25 4
gpt4 key购买 nike

我正在尝试将 thead 和 tbody 标签添加到我的 react 表中。源数据是一个数组,其中第一个索引包含表头,其余是表体。

    return (
<div>
{index == 1 && <tbody>}
<tr key={index}>
{tableData(false, row.value)}
</tr>
{index == pivot.data.table.length && </tbody>}
</div>
);

在上面的循环中,我在 {index == pivot.data.table.length && </tbody>} 处获得了意外的 token

完整代码和沙箱如下:

import React, { Component } from "react";
import { render } from "react-dom";
import Pivot from "quick-pivot";
import { Table } from 'react-bootstrap';

class PivotTable extends Component {
constructor(props) {
super(props);
}

createTable() {
const dataArray = [
["name", "gender", "house", "age"],
["Jon", "m", "Stark", 14],
["Arya", "f", "Stark", 10],
["Cersei", "f", "Baratheon", 38],
["Tywin", "m", "Lannister", 67],
["Tyrion", "m", "Lannister", 34],
["Joffrey", "m", "Baratheon", 18],
["Bran", "m", "Stark", 8],
["Jaime", "m", "Lannister", 32],
["Sansa", "f", "Stark", 12]
];

const rowsToPivot = ["name"];
const colsToPivot = ["house", "gender"];
const aggregationDimension = "age";
const aggregator = "sum";

const pivot = new Pivot(
dataArray,
rowsToPivot,
colsToPivot,
aggregationDimension,
aggregator
);

console.log("pivot.data", pivot.data, "pivot.data.table", pivot.data.table);
const tableData = (heading, row) => {
return row.map(cell => {
if (heading) {
return (
<th>
{cell}
</th>
);
} else {
return (
<td>
{cell}
</td>
);
}
});
};

return pivot.data.table.map((row, index) => {
if (index == 0) {
return (
<thead>
<tr key={index}>
{tableData(true, row.value)}
</tr>
</thead>
);
} else {
return (
<div>
{index == 1 && <tbody>}
<tr key={index}>
{tableData(false, row.value)}
</tr>
{index == pivot.data.table.length && </tbody>}
</div>
);
}
});
}

render() {
return (
<table>
{this.createTable()}
</table>
);
}
}

render(<PivotTable />, document.getElementById("root"));

沙盒: https://codesandbox.io/s/vgDE6rOEM

我该如何解决这个问题?

我认为最简单的方法是创建一个单独的函数,再次调用数据,创建一个新数组并且仅创建标题。当我这样做时,问题是它可能会大大降低性能。

我可以通过一次通话解决所有问题吗?或者解决此问题的最佳方法是什么?

最佳答案

我通常使用三元运算符来实现此类模式,请尝试:

return (
<div>
{index == 1 ? <tbody> : <div />}
<tr key={index}>
{tableData(false, row.value)}
</tr>
{index == pivot.data.table.length ? </tbody> : <div />}
</div>
);

关于javascript - 在react中使用thead和tbody标签循环遍历数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45552693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com