在材质 ui 中创建的目标 CSS 子选择器

时间:2021-01-26 03:57:35

标签: reactjs material-ui

我有这样的风格:

const useStyles = makeStyles(theme => ({
  root: {
    margin: 5
  },
  container: {
    backgroundColor: 'red'
  },
  active: {
    // here I want to target the 'container' className I created above like
    '& .container': {
      backgroundColor: 'green'
    }
  }
});

我想定位我在 container className 中创建的 active className。以上将不起作用,因为在 DOM 中,MUI 将 generate 一个唯一的名称,因此我不会定位正确的类。无法找到解决此问题的任何 SO 答案或博客或文档。

3 个答案:

答案 0 :(得分:2)

您可以使用 $

引用

您必须稍微修改 DOM,使 active className 不是 container 的父级。而是将 active className 添加到 conatiner 元素本身。

所以你的 css 样式可能如下所示

const useStyles = makeStyles(theme => ({
  root: {
    margin: 5
  },
  container: {
    backgroundColor: 'red',
    
    '&$active': {
      backgroundColor: 'green'
    }
  },
  
});

答案 1 :(得分:1)

我认为这就是您要找的$rulename

如何使用 $ruleName 在同一个样式表中引用本地规则

在你的情况下,我认为解决方案是

const useStyles = makeStyles(theme => ({
  root: {
    margin: 5
  },
  container: {
    backgroundColor: 'red'
  },
  active: {
    .container: {
      backgroundColor: 'green'
    }
  }
});


   Which should compile to 

.root.container.active{} 并在目标标签上以按钮为例

 <Button
  classes={{
    root: classes.root,
    container: classes.container,
    active: classes.active,
  }}>

尚未使用 MUI,但即使在 vue 或 react 中,实现此目的的方式也是通过在通过脚本定位的标签上设置动态名称。

答案 2 :(得分:1)

$ rulename 用于此目的。 Here 是 Material-UI 上的文档。

CSS in JS 文档也解释了此功能。

container: {
  //other styles
},
active: {
  "& $container": {
    background: "green",
    color: "#fff"
  }
}

这里有一件很重要的事情,即引用 'containerrule, it should be defined in the rules object. trying to use"& $containerwithout defining thecontainerrule inside themakeStyles` 将不起作用。

这是工作演示:

Edit nested rulename selector