如何为嵌套数组的HTML表格添加表头?
解决嵌套数组渲染表格的表头对齐问题
你当前的代码存在HTML结构错误——在<td>标签内部嵌套了<tr>,这不符合表格的规范,导致浏览器解析混乱,表头和内容列无法正确对应。下面给出两种针对性的解决方案:
方案1:仅展示学生数据(无需部门分组)
直接将嵌套的department数组扁平化,把所有学生数据统一映射为表格行,这样表头就能和内容列完美对齐:
const Table = college?.flatMap(collegeItem => collegeItem.department.map(student => ( // 添加唯一key避免React警告 <tr key={`${collegeItem.id}-${student.id}`}> <td>{student.studentName}</td> <td>{student.subject}</td> <td>{student.daysClassattended}</td> </tr> )) ); return ( <div> <table> <thead> <tr> <th>Student Name</th> <th>Subject</th> <th>Days Attended Classes</th> </tr> </thead> <tbody>{Table}</tbody> </table> </div> );
方案2:按部门分组展示(带部门标题)
如果需要显示部门信息,可以用单元格合并的方式,既保持结构规范,又能清晰分组:
方式A:部门标题跨列作为分组行
const Table = college?.flatMap(collegeItem => [ // 部门标题行,跨3列显示部门名称 <tr key={`dept-${collegeItem.id}`}> <th colSpan={3}>{collegeItem.departmentName}</th> </tr>, // 该部门下的所有学生行 ...collegeItem.department.map(student => ( <tr key={`student-${student.id}`}> <td>{student.studentName}</td> <td>{student.subject}</td> <td>{student.daysClassattended}</td> </tr> )) ]); return ( <div> <table> <thead> <tr> <th>Student Name</th> <th>Subject</th> <th>Days Attended Classes</th> </tr> </thead> <tbody>{Table}</tbody> </table> </div> );
方式B:部门作为单独列,跨行合并
const Table = college?.flatMap(collegeItem => collegeItem.department.map((student, index) => ( <tr key={`${collegeItem.id}-${student.id}`}> {/* 仅该部门第一个学生显示部门名称,跨行覆盖整个部门的行 */} {index === 0 && ( <td rowSpan={collegeItem.department.length}>{collegeItem.departmentName}</td> )} <td>{student.studentName}</td> <td>{student.subject}</td> <td>{student.daysClassattended}</td> </tr> )) ); return ( <div> <table> <thead> <tr> <th>Department</th> <th>Student Name</th> <th>Subject</th> <th>Days Attended Classes</th> </tr> </thead> <tbody>{Table}</tbody> </table> </div> );
内容的提问来源于stack exchange,提问作者user20183888
相关产品推荐
相关产品推荐

