You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React TSX中如何正确将嵌套数组映射至表格对应列?

解决React TSX中嵌套数组映射表格的问题

你的核心问题是表格主体的映射逻辑错误:原代码只生成了一行<tr>,并试图从每个bodyItems数组中取对应索引的元素塞到这一行的列里,完全不符合“每个数组对应一行、数组元素对应列”的需求。

修正后的代码

import { Container, Table } from 'react-bootstrap'; // 假设你使用react-bootstrap组件库

const headers = [['a', 'b', 'c', 'd', 'e', 'f', 'g']];
const bodyItems = [ 
['1', '2', '3', '4', '5', '6', '7'],
['1a', '2a', '3a', '4a', '5a', '6a', '7a'],
['1b', '2b', '3b', '4b', '5b', '6b', '7b'],
['1c', '2c', '3c', '4c', '5c', '6c', '7c'],
['1d', '2d', '3d', '4d', '5d', '6d', '7d'],
['1e', '2e', '3e', '4e', '5e', '6e', '7e'],
['1f', '2f', '3f', '4f', '5f', '6f', '7f']
];

export const OutputDataTable = () => {
    return (
        <div>
            <Container style={{ marginTop: '1rem' }}>
                <Table className="table table-bordered table-striped">
                    <thead>
                        <tr>
                            {headers[0].map((title, index) => (
                                <th scope='col' key={index}>{title}</th>
                            ))}
                        </tr>
                    </thead>
                    <tbody>
                        {/* 遍历bodyItems生成每一行 */}
                        {bodyItems.map((row, rowIndex) => (
                            <tr key={rowIndex}>
                                {/* 遍历当前行的元素生成每一列 */}
                                {row.map((cell, cellIndex) => (
                                    <td key={cellIndex}>{cell}</td>
                                ))}
                            </tr>
                        ))}
                    </tbody>
                </Table>
            </Container>
        </div>
    )
}

export default OutputDataTable;

关键修正说明

  • 表格结构调整:原代码仅创建一个<tr>,现在改为遍历bodyItems,让每个数组对应一个独立的表格行
  • 列映射逻辑修正:在每个<tr>内部,遍历当前行数组的所有元素生成<td>,确保每个元素对应表头的独立列
  • key值说明:示例中用索引作为key适用于静态数据场景,如果是动态数据,建议使用单元格的唯一标识作为key,避免渲染异常

内容的提问来源于stack exchange,提问作者Joshua

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 22:05:14