如何更改材料ui表的悬停颜色

Nay*_*ava 9 reactjs material-ui

我正在为我的Web应用程序使用React和Material UI.我想更改表行的悬停颜色但不能这样做.

示例代码

x={
  hover:{
    color:'green'
 }
}

<TableRow hover
          key={lead.id} className={classes.row}
          classes={{
                    hover:x.hover
                   }}
          onClick={() => {}}>
Run Code Online (Sandbox Code Playgroud)

Nea*_*arl 11

这在MUI v5中是一个微不足道的任务。请参阅此处的文档:

<Table
  sx={{
    "& .MuiTableRow-root:hover": {
      backgroundColor: "primary.light"
    }
  }}
>
Run Code Online (Sandbox Code Playgroud)

现场演示

Codesandbox 演示


Sak*_*oor 7

到目前为止,我已经有了这个解决方案。也许还有其他方法可以覆盖 tableRow 的 css ,但这个方法很有魅力:

const styles = theme => ({
tableRow: {
    "&:hover": {
      backgroundColor: "blue !important"
    }
  }
});


<TableRow hover
      key={lead.id} className={classes.tableRow}

      onClick={() => {}}>
Run Code Online (Sandbox Code Playgroud)

随时提出任何问题。


Jef*_*rdt 6

以防万一,如果您正在使用组件覆盖并想要进行样式覆盖,您必须定位根而不是悬停规则。我花了很长时间试图让伪 :hover 来解决这个问题,但它永远不会起作用。

这就是我所拥有的。

MuiTableRow: {
    styleOverrides: {
        // Even though there is a hover rule we have to override it here. Don't ask.
        root: {
            '&.MuiTableRow-hover:hover': {
                backgroundColor: 'blue',
            },
        },
    },
},
Run Code Online (Sandbox Code Playgroud)

如果您想要在主题级别覆盖组件而不是样式覆盖、sx 或 useStyles,请使用此选项。


小智 5

tableRow: {
    hover: {
        "&$hover:hover": {
            backgroundColor: '#49bb7b',
        },
    },
}

<TableRow className={classes.tableRow} key={n.id} hover onClick={event => this.handleClick(event)}>Text</TableRow>
Run Code Online (Sandbox Code Playgroud)

  • 请对该代码添加一些解释,以便其他人可以从中学习 (3认同)

art*_*jpm 5

只需将鼠标悬停在 TableRow 中,而不是标题 Tablerow

 <StyledTableRow hover key={row.name}>
Run Code Online (Sandbox Code Playgroud)

@material-ui/core/TableRow 内置了处理悬停的代码,它对我有用。


use*_*676 5

TableRow 组件自定义组件页面的实现表明您需要重写两个类 root.hover:hover 和 .hover 来更改悬停颜色。

const useStyles = makeStyles((theme) => ({
  /* Styles applied to the root element. */
  root: {
    // Default root styles
    color: 'inherit',
    display: 'table-row',
    verticalAlign: 'middle',
    // We disable the focus ring for mouse, touch and keyboard users.
    outline: 0,

    '&$hover:hover': {
      // Set hover color
      backgroundColor: theme.palette.action.hover,
    },
  },

  /* Pseudo-class applied to the root element if `hover={true}`. */
  hover: {},
}));
Run Code Online (Sandbox Code Playgroud)

然后在您的组件中,您可以将样式应用到classes 属性。

const HelloWorld = () => {
  const classes = useStyles();
  return (
    <TableRow classes={classes}><TableCell></TableCell></TableRow>
  );
};
Run Code Online (Sandbox Code Playgroud)