React表格映射渲染异常:如何让地址内容正确对应表头显示?
Fixing Your Material-UI Table Rendering Issue
Got it, let's figure out why your table isn't displaying correctly. The problem here is how you're inserting your generated rows into the TableBody—you're wrapping the entire addressTd array (which is a list of TableRow components) inside a single TableCell, which shoves all your rows into one column instead of mapping them properly to each row/column.
Here's the Fix:
Instead of wrapping addressTd in a TableCell, you can directly render the array inside TableBody since TableBody accepts multiple TableRow components as children.
Corrected Code:
// Your row mapping remains the same (added a key prop for best practices) const addressTd = addressesInfo.map(item => ( <TableRow key={item.id}> {/* Use a unique value from your item, like an ID */} <TableCell align="right">{item.officeName}</TableCell> <TableCell align="right">{item.address1}</TableCell> </TableRow> )); // Updated return structure return ( <Table> <TableHead> <TableRow> <TableCell>Office Name</TableCell> <TableCell>Address Line 1</TableCell> </TableRow> </TableHead> <TableBody> {addressTd} {/* Directly render the TableRow array here */} </TableBody> </Table> );
Key Notes:
- Unique Key Prop: I added
key={item.id}to theTableRowinside your map—React requires a unique key for list items to optimize re-renders. Always use a stable, unique identifier from your data (like an item ID) instead of the array index if possible. - TableBody Children:
TableBodyexpectsTableRowcomponents as direct children, notTableCell. By removing the wrappingTableCell, each generatedTableRowwill correctly correspond to a row in your table, with each innerTableCellaligning to the columns you defined inTableHead.
This should make your office names and addresses line up properly under their respective columns!
内容的提问来源于stack exchange,提问作者Broken Mind
相关产品推荐
相关产品推荐

