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 forMake,Model,Year, we now loop over thethis.props.orderarray again for each row. This ensures the data cells follow exactly the same order as the headers. - Added a type assertion
column as keyof Carto satisfy TypeScript, since we need to confirm that each string in theorderarray corresponds to a valid property on theCarobject. - Updated the keys for the table rows and cells to be more appropriate:
rowKeyfor each car row, andcolKeyfor 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
相关产品推荐
相关产品推荐

