如何自定义Material UI可排序选择类型表格选中行的默认颜色
Material-UI 可选择表格自定义选中行颜色方案
MUI v5 版本操作方法
- 仅修改当前页面表格选中色为primary蓝色
直接在TableRow组件上添加sx属性覆盖选中样式即可,代码示例:<TableRow hover key={row.id} selected={isItemSelected(row.id)} sx={{ '&.Mui-selected': { backgroundColor: 'primary.main', '&:hover': { backgroundColor: 'primary.light' } } }} > {/* 行内容 */} </TableRow> - 使用自定义颜色
直接替换上面的色值为你需要的颜色即可,示例:sx={{ '&.Mui-selected': { backgroundColor: '#d1ecf1', '&:hover': { backgroundColor: '#bee5eb' } } }} - 全局修改所有表格选中行颜色
在全局主题配置中添加样式覆盖:
再用import { createTheme, ThemeProvider } from '@mui/material/styles'; const theme = createTheme({ components: { MuiTableRow: { styleOverrides: { root: { '&.Mui-selected': { backgroundColor: 'primary.main', '&:hover': { backgroundColor: 'primary.light' } } } } } } });ThemeProvider包裹你的项目根组件即可全局生效。
MUI v4 版本操作方法
- 局部修改单个表格的选中色
用withStyles高阶组件封装自定义的TableRow:
替换原来的import { withStyles } from '@material-ui/core/styles'; import TableRow from '@material-ui/core/TableRow'; const StyledTableRow = withStyles((theme) => ({ root: { '&$selected': { backgroundColor: theme.palette.primary.main, '&:hover': { backgroundColor: theme.palette.primary.light, }, }, }, selected: {}, }))(TableRow);TableRow组件使用即可。 - 全局修改所有表格选中色
在创建主题时覆盖组件默认样式:
用import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles'; const theme = createMuiTheme({ overrides: { MuiTableRow: { root: { '&$selected': { backgroundColor: '你需要的颜色值', '&:hover': { backgroundColor: '对应hover状态的颜色值' } } } } } });MuiThemeProvider包裹根组件即可全局生效。
内容的提问来源于stack exchange,提问作者Carlos D. Zapata
相关产品推荐
相关产品推荐

