MUI可展开表格隔行变色失效问题求助
问题原因
你的Row组件每个实例会返回两个<TableRow>(主数据行+展开详情行),导致<TableBody>中的DOM结构变成:TableRow(主行1) → TableRow(展开行1) → TableRow(主行2) → TableRow(展开行2)...
所有主行都处于DOM的奇数位置(第1、3、5...个TableRow),全部匹配&:nth-of-type(odd)的绿色样式,这就是所有主行显示为绿色的核心原因。
解决方案
推荐两种可靠的修复方式:
方案一:基于数据索引手动控制背景色(最稳定)
直接通过数据的索引判断奇偶,不受DOM结构干扰:
- 父组件调用
Row时传入数据索引:
<TableBody> {rows.map((row, index) => ( <Row key={row.id} row={row} index={index} /> ))} </TableBody>
- 修改
Row组件,根据索引设置背景色:
function Row(props) { const { row, index } = props; const StyledTableRow = styled(TableRow)(({ theme }) => ({ backgroundColor: index % 2 === 0 ? "green" : "grey", })); return ( <React.Fragment> <StyledTableRow sx={{ '& > *': { borderBottom: 'unset' } }}> <IconButton aria-label="expand row" size="small" onClick={() => setOpen(!open)} > {open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />} </IconButton> <TableCell component="th" scope="row">{row.Type}</TableCell> <TableCell align="right">{row.Mix}</TableCell> <TableCell align="right">{row.SVC}</TableCell> <TableCell align="right">{row.AR}</TableCell> <TableCell align="right">{row.Discount}</TableCell> </StyledTableRow> <TableRow> <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={8}> <Collapse in={open} timeout="auto" unmountOnExit> <Box sx={{ margin: 1 }}> <Table size="small" aria-label="purchases"> <TableBody> <TableRow> .................. </TableRow> </TableBody> </Table> </Box> </Collapse> </TableCell> </TableRow> </React.Fragment> ); }
方案二:调整CSS选择器,跳过展开行计数
给展开行标记专属类名,让选择器只针对主行计算奇偶:
function Row(props) { const { row } = props; const StyledTableRow = styled(TableRow)(({ theme }) => ({ '&:not(.expand-row):nth-of-type(odd)': { backgroundColor: "green", }, '&:not(.expand-row):nth-of-type(even)': { backgroundColor: "grey", }, })); // 给展开行定义透明背景,避免干扰视觉 const ExpandTableRow = styled(TableRow)({ backgroundColor: "transparent", className: "expand-row" }); return ( <React.Fragment> <StyledTableRow sx={{ '& > *': { borderBottom: 'unset' } }}> {/* 主行内容不变 */} </StyledTableRow> {/* 使用带类名的展开行组件 */} <ExpandTableRow> {/* 展开行内容不变 */} </ExpandTableRow> </React.Fragment> ); }
内容的提问来源于stack exchange,提问作者SM079
相关产品推荐
相关产品推荐

