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

ReactJS:实现表格表头列顺序变更时数据列同步联动

Fix: Sync Table Data Cells with Dynamic Column Order in React CarTable

The core issue here is that your table's data cells (<td>) are hardcoded in a fixed order, while the headers (<th>) are dynamically rendered based on the order prop. To fix this, you need to make the data cells dynamically match the column order just like the headers do.

Here's the updated CarTable.tsx that solves the problem:

import React from 'react';
import './App.css';
import { Car } from './Models/Car';

export default class CarTable extends React.Component<any, any> {
  render() {
    return(
      <table id="carsTable">
        <thead>
          <tr>
            {this.props.order.map((column: string, key: any) => {
              return(<th key={column}>{column}</th>)
            })}
          </tr>
        </thead>
        <tbody>
          {this.props.cars.map((car: Car, rowKey: any) => {
            return(
              <tr key={rowKey}>
                {/* Dynamically render TDs based on the current column order */}
                {this.props.order.map((column: string, colKey: any) => {
                  // Use type assertion to tell TypeScript column is a valid key of Car
                  return <td key={colKey}>{car[column as keyof Car]}</td>;
                })}
              </tr>
            )
          })}
        </tbody>
      </table>
    )
  }
}

Key Changes Explained:

  • Instead of hardcoding <td> elements for Make, Model, Year, we now loop over the this.props.order array again for each row. This ensures the data cells follow exactly the same order as the headers.
  • Added a type assertion column as keyof Car to satisfy TypeScript, since we need to confirm that each string in the order array corresponds to a valid property on the Car object.
  • Updated the keys for the table rows and cells to be more appropriate: rowKey for each car row, and colKey for each data cell (using the index from the column loop works well here, or you could use the column name itself).

Now when you click the "Change Column Order" button, both the headers and the data cells will reorder in sync, so the Make data always appears under the Make header, Year under Year, etc.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:41:18