提问者:小点点

无法在material-ui中用类覆盖样式


我使用material-ui中的TableRow组件实现了一个表,它有一个名为“Selected”的属性。只要“selected”为true,就会为其应用一个粉红色的背景色(来自默认主题)。我试图更改这个默认的粉色,根据文档,我选择覆盖css类,比如:

const styles = theme => ({
  rowSelected: {
    backgroundColor: theme.palette.grey[700]
  }
})
class CustomTableRow extends React.Component {
// basic component logic
render() {
const {classes, className, style } = this.props;
  <TableRow
    key={key}
    component="div"
    selected={true}
    hover={true}
    className={className}
    classes={{ selected: classes.rowSelected}}
    style={style}
  >
      // some children
  </TableRow>
}
export default withStyles(styles, { withTheme: true })(CustomTableRow);

但这并没有奏效,这很让人困惑。因为我已经成功地在其他地方用上面相同的方法对抽屉组件执行了相同的操作。

我用Chrome开发工具调试了每个css属性。我现在最怀疑的是,粉红色用下面这样的方式应用在这个组件上:

.MuiTableRow-root.Mui-selected, .MuiTableRow-root.Mui-selected:hover {
    background-color: rgba(245, 0, 87, 0.16);

我的自定义类样式的优先级比这一个低,这一个是灰色的。

更新1:

我的项目太大了,我不知道如何为CodeSandBox.io简化它。也许我们可以直接查看material-ui源代码,TableRow源代码。我所做的是在root中重写这个css声明

    '&$selected, &$selected:hover': {
      backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.selectedOpacity),
    },

通过在下面传入另一个selected声明。我意识到这是因为这个&$selected,&$selected:hover通常不是css,即使我把它复制到rowselected中,它也不起作用。

更新2:

我设法用“!重要”关键字覆盖了backgroundColor:

const styles = theme => ({
  rowSelected: {
    backgroundColor: theme.palette.grey[700] + " !important",
  }
})

我不知道这是否是一个理想的解决方案。这清楚地表明了css的问题是关于类优先级的。因此如何使用类selected重写类root中已定义backgroundColor。

请帮忙,谢谢。


共1个答案

匿名用户

若要为所选类提供特定性,可以将$selected$selected:Hover类应用于重写,如下所示

const styles = theme => ({
  rowSelected: {
    "&$selected, &$selected:hover": {
      backgroundColor: theme.palette.grey[800]
    }
  }
})

示例演示