如何调整MUI中TableRow的高度?尝试设置未生效
解决MUI TableRow高度无法调整的问题
MUI的TableRow和TableCell默认带有内边距与最小高度限制,直接设置height会被这些默认样式覆盖,以下是可行的调整方案:
1. 调整TableCell的内边距与最小高度
给所有TableCell添加样式,覆盖默认的内边距和最小高度,同时确保内容垂直居中:
<TableCell key={th.id} align={th.align ? th.align : "center"} className="text-xs" size="small" sx={{ padding: '4px 8px', // 按需减小内边距 minHeight: '10px', // 覆盖默认最小高度 height: '10px', display: 'flex', alignItems: 'center' }} > {th.render ? th.render(row[th.id.toString()], row) : row[th.id.toString()]} </TableCell>
2. 同步设置TableRow的高度与对齐
给MuiTableRow设置高度,并确保行内元素垂直对齐:
<MuiTableRow sx={{ "&:last-child td, &:last-child th": { border: 0 }, height: '10px', alignItems: 'center' }} > {/* 单元格内容 */} </MuiTableRow>
3. 调整操作列IconButton的内边距
操作列中的IconButton默认内边距较大,会撑高行,需要单独调整:
<IconButton aria-label={action.id} onClick={() => (action?.onClick ? action.onClick(row) : null)} sx={{ padding: '4px' }} // 减小图标按钮的内边距 > {action.icon} </IconButton>
修改后的完整核心组件代码
const ActionItem: React.FC<ActionItemProps> = memo(({ action, row }) => { return action?.onClick ? ( <Tooltip key={action.id} title={action.label}> <IconButton aria-label={action.id} onClick={() => (action?.onClick ? action.onClick(row) : null)} sx={{ padding: '4px' }} > {action.icon} </IconButton> </Tooltip> ) : action?.href ? ( <Tooltip key={action.id} title={action.label}> <NavLink to={typeof action.href === "function" ? action.href(row) : action.href} style={{ padding: '4px', display: 'flex', alignItems: 'center' }} > {action.icon} </NavLink> </Tooltip> ) : null; }); const TableRow: React.FC<ItemProps> = ({ row, head, actions }) => ( <MuiTableRow sx={{ "&:last-child td, &:last-child th": { border: 0 }, height: '10px', alignItems: 'center' }} > {head.map((th) => ( <TableCell key={th.id} align={th.align ? th.align : "center"} className="text-xs" size="small" sx={{ padding: '4px 8px', minHeight: '10px', height: '10px', display: 'flex', alignItems: 'center' }} > {th.render ? th.render(row[th.id.toString()], row) : row[th.id.toString()]} </TableCell> ))} {actions && actions.length > 0 && ( <TableCell align="center" sx={{ padding: '4px 8px', minHeight: '10px', height: '10px', display: 'flex', alignItems: 'center', gap: '4px' }} > {actions.map((action) => ( <ActionItem key={action.id} action={action} row={row} /> ))} </TableCell> )} </MuiTableRow> );
内容的提问来源于stack exchange,提问作者Mehrdad Karami Jourabi
相关产品推荐
相关产品推荐

