【问题标题】:Change color of selected row on Material UI table更改 Material UI 表上选定行的颜色
【发布时间】:2021-10-06 22:02:57
【问题描述】:

如何更改/自定义 Material-UI 表(排序和选择类型)中选定行的默认颜色?默认情况下,它是次要(红色)颜色(此处的代码沙箱:https://codesandbox.io/s/3sjxh)。如何将其更改为自定义颜色,或至少更改为主要颜色(蓝色),因为它出现在新的 beta 版本 (https://next.material-ui.com/components/tables/#main-content) (v5) 中。

【问题讨论】:

    标签: material-ui


    【解决方案1】:

    您必须将样式传递给 classes 属性才能更改 TableRow 的样式。

    要实现 background-color 更改,您需要覆盖默认类:.MuiTableRow-root.Mui-selected.MuiTableRow-root.Mui-selected:hover

    要覆盖它们,您必须在 makeStyles 挂钩中使用带有所谓的 $ruleName 的父引用。 Here is a very good explanation from @Ryan Cogswell if you are more interested how it works.

    这将如下所示:

    const useStyles = makeStyles((theme) => ({
      // your other styles
      ...,
      tableRowRoot: {
        "&$tableRowSelected, &$tableRowSelected:hover": {
          backgroundColor: theme.palette.primary.main
        }
      },
      tableRowSelected: {
        backgroundColor: theme.palette.primary.main
      }
    }));
    
    ...
    
    <TableRow
      // your other props
      ...
      classes={{
        root: classes.tableRowRoot,
        selected: classes. tableRowSelected,
      }}
    >
      ...
    </TableRow>;
    

    对于复选框,您只需添加 color 属性即可更改它:

    <Checkbox
      // other props
      ...
      color="primary"
    />
    

    对于您的Toolbar,您只需更改useToolbarStyles 中提供的highlight 类即可使事情正常进行:

    import { alpha } from "@material-ui/core/styles";
    
    ...
    
    const useToolbarStyles = makeStyles((theme) => ({
      ...,
      highlight:
        theme.palette.type === "light"
          ? {
              color: theme.palette.primary.main,
              backgroundColor: alpha(
                theme.palette.primary.light,
                theme.palette.action.selectedOpacity
              )
            }
          : {
              color: theme.palette.text.primary,
              backgroundColor: theme.palette.primary.dark
            },
    }));
    

    现场演示:

    【讨论】:

    • 非常感谢!我认为它指向那个方向,但不知道 $ruleName。也感谢您的链接,确实非常有用!
    猜你喜欢
    • 2019-03-20
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 2017-03-12
    • 1970-01-01
    • 2021-09-27
    相关资源
    最近更新 更多