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

ReactJS中如何垂直映射表格行?解决数据横向排列问题

React表格数据垂直排列问题解决

你的问题出在所有表格单元格都被包裹在同一个<tr>标签内,导致数据横向挤在一行里。要实现垂直排列,每个数据项需要对应独立的表格行(<tr>),每行包含对应列的单元格。

修正后的代码

function App() {
  let response = [
    {
      id: 134,
      user_name: 'abc',
      phone_number: 1234567890,
      children: [
        { id: 659, user_name: 'ghi', phone_number: 9834763467 },
        { id: 659, user_name: 'ghi', phone_number: 9834763467 },
      ],
    },
    {
      id: 948,
      user_name: 'def',
      phone_number: 9823437483,
      children: [
        { id: 659, user_name: 'ghi', phone_number: 9834763467 },
        { id: 659, user_name: 'ghi', phone_number: 9834763467 },
      ],
    },
    {
      id: 865,
      user_name: 'abc',
      phone_number: 1234567890,
      children: [
        { id: 659, user_name: 'ghi', phone_number: 9834763467 },
        { id: 659, user_name: 'ghi', phone_number: 9834763467 },
      ],
    },
  ];

  return (
    <div className="App">
      <table>
        <thead>
          <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Phone Number</th>
          </tr>
        </thead>
        <tbody>
          {/* 每个数据项对应一行 */}
          {response.map((value, index) => (
            <tr key={index}>
              <td>{value.id}</td>
              <td>{value.user_name}</td>
              <td>{value.phone_number}</td>
              {/* 可选:展示子数据,不需要可删除 */}
              {value.children.map((child, childIndex) => (
                <tr key={`${index}-${childIndex}`}>
                  <td>{child.id}</td>
                  <td>{child.user_name}</td>
                  <td>{child.phone_number}</td>
                </tr>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default App;

关键改动说明

  • 将response.map移到<tbody>下,直接返回<tr>元素,让每个数据对象对应一行
  • 给动态生成的列表元素添加key属性(React要求列表项必须有唯一标识)
  • 每行内严格对应Id、Name、Phone Number三列的单元格
  • 额外提供了子数据的渲染示例,不需要可直接删除该部分代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 17:07:46