MUI V5折叠表格隔行背景色失效问题求助
解决MUI V5可折叠表格隔行变色失效问题
问题根源
你的代码失效是因为可折叠表格中,主数据行和折叠详情行都会被<TableRow>渲染,:nth-of-type(odd)会把两类行一起计入计数,导致奇偶判断逻辑混乱,最终所有行都呈现灰色。
解决方案
1. 区分主行与折叠行
仅对主数据行应用自定义样式的StyledTableRow,折叠详情行使用原生TableRow(不附加隔行变色样式)。
2. 调整样式代码
修改StyledTableRow的样式,建议使用MUI主题色替代硬编码的grey,提升样式兼容性:
const StyledTableRow = styled(TableRow)(({ theme }) => ({ "&:nth-of-type(odd)": { backgroundColor: theme.palette.grey[100], // 浅灰色,与默认行背景区分 }, "&:last-child td, &:last-child th": { border: 0, }, }));
3. 组件渲染示例
{rows.map((row) => ( <React.Fragment key={row.id}> {/* 主数据行:应用StyledTableRow */} <StyledTableRow> <TableCell> <IconButton aria-label="expand row" size="small" onClick={() => handleRowClick(row.id)} > {isRowExpanded(row.id) ? <ExpandLess /> : <ExpandMore />} </IconButton> </TableCell> <TableCell component="th" scope="row">{row.name}</TableCell> <TableCell align="right">{row.calories}</TableCell> {/* 其他单元格 */} </StyledTableRow> {/* 折叠详情行:使用原生TableRow,不应用隔行样式 */} <TableRow> <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={4}> <Collapse in={isRowExpanded(row.id)} timeout="auto" unmountOnExit> <Box sx={{ margin: 1 }}> <Typography variant="h6" gutterBottom component="div"> 详情内容 </Typography> {/* 折叠区域内容 */} </Box> </Collapse> </TableCell> </TableRow> </React.Fragment> ))}
通过以上调整,:nth-of-type(odd)只会对主数据行计数,就能实现正常的隔行变色效果,同时折叠行不会干扰样式逻辑。
内容的提问来源于stack exchange,提问作者seenumk
相关产品推荐
相关产品推荐

