如何为MUI表格列着色?及useTheme使用rgba颜色的疑问
MUI表格列着色及主题颜色调用问题解决
问题说明
- 需求是给MUI表格的
name列设置绿色背景,初期知道要遍历列时判断列名,但不清楚具体实现方式 - 后续实现列着色后,无法通过
useTheme钩子调用主题中的rgba颜色值,需要解决该问题
初始代码示例
const data = [{name: "jack", age: 22}, {name: "Robert", age: 33}]; const headers = ["name", "age"]; <TableContainer component={Paper} sx={{ flex: 1, flexBasis: 0, flexDirection: 'column' }}> <Table stickyHeader aria-label="test table" size="small"> <TableHead> <TableRow aria-label="test table"> {headers.map((item, idx) => { return ( <TableCell sx={{pl:1, pr:1}} key={idx}> {item} </TableCell> ); })} </TableRow> </TableHead> <TableBody> {data.map((record, rowid) => { return ( <TableRow key={rowid} sx={{'&:last-child td, &:last-child th': {border: 0}}}> {headers.map((item, tableidx) => ( <TableCell size="small" sx={{pr: 1, pl:1}} key={tableidx}> {record[item]} </TableCell> ))} </TableRow> ); })} </TableBody> </Table> </TableContainer>
优化后代码片段
{index?.map((idx) => initialTable[idx]).map((row, rowid) => { return ( <TableRow sx={{ '&:last-child td, &:last-child th': {border: 0}, ...(rowid % 2 && { backgroundColor: theme.palette.action.hover }) }} key={rowid} > {columns.map((item, tableidx) => ( <TableCell size="small" sx={{ pr: 1, pl: 1, ...(item === 'ticker' && {backgroundColor: 'yellow'}), ...(item === 'volatility' && { backgroundColor: 'rgba(255, 185, 0, 0.4)', }), }} key={tableidx} > {/* 单元格内容 */} </TableCell> ))} </TableRow> ); })}
解决方案
1. 实现指定列(name)着色
在遍历表头和表体的TableCell时,通过判断列名添加背景色样式:
// 表头部分 <TableCell sx={{ pl: 1, pr: 1, ...(item === 'name' && { backgroundColor: '#4caf50' }) }} key={idx} > {item} </TableCell> // 表体部分 <TableCell size="small" sx={{ pr: 1, pl: 1, ...(item === 'name' && { backgroundColor: '#4caf50' }) }} key={tableidx} > {record[item]} </TableCell>
2. 正确使用useTheme调用主题rgba颜色值
步骤1:导入useTheme钩子
import { useTheme } from '@mui/material/styles';
步骤2:在组件内获取主题对象
const theme = useTheme();
步骤3:在sx属性中使用主题颜色(支持透明度)
MUI主题颜色支持两种方式添加透明度:
- 方式一:在十六进制颜色末尾添加两位透明度值(如
40对应0.4)
<TableCell size="small" sx={{ pr: 1, pl: 1, ...(item === 'volatility' && { backgroundColor: `${theme.palette.warning.main}40` }), }} > {/* 内容 */} </TableCell>
- 方式二:使用
rgba()函数,先将主题十六进制颜色转为RGB值
// 自定义十六进制转RGB函数 const hexToRgb = (hex) => { const r = parseInt(hex.slice(1, 3), 16); const g = parseInt(hex.slice(3, 5), 16); const b = parseInt(hex.slice(5, 7), 16); return `${r}, ${g}, ${b}`; }; // 在sx中使用 <TableCell size="small" sx={{ pr: 1, pl: 1, ...(item === 'volatility' && { backgroundColor: `rgba(${hexToRgb(theme.palette.warning.main)}, 0.4)` }), }} > {/* 内容 */} </TableCell>
注意事项
- 不要在
style属性中使用theme,style只接受纯CSS对象,无法访问主题上下文;必须使用MUI的sx属性来获取主题。 - 确保组件在
ThemeProvider的包裹范围内,否则useTheme无法获取到主题对象。
内容的提问来源于stack exchange,提问作者turtle_in_mind
相关产品推荐
相关产品推荐

