繁体   English   中英

关于将样式组件与 material-ui 混合的问题

[英]Question about mixing styled-components with material-ui

您好,我是一个反应新手,并且对样式也很陌生:) 我正在尝试使用样式组件来设置 material-ui Button 组件的样式

我通过覆盖全局 class 名称来做到这一点,我知道 material-ui 引入了全局 class 名称,例如 MuiButton-root 等

我不清楚在父选择器中使用“&” ,例如:

const StyledButton = styled(Button)`
  &.MuiButton-root {
    width: 500px;
  }

  .MuiButton-label {
    color: ${props => props.labelColor};
    justify-content: center;
  }
`;

上面的代码有效,可以实现以下效果:

  • 按钮的宽度为 500px
  • label 的颜色为红色(labelColor 作为道具传入)
  • 请参阅下面的沙箱以获取完整代码

问题:为什么 MuiButton-root 需要“&”选择器,而 MuiButton-label 我不需要?

这也是使用样式组件设计 material-ui 的最佳方式吗?

请查看以下沙箱: https://codesandbox.io/embed/practical-field-sfxcu

'&' 选择器用于定位类和相邻元素/类。 看看cssinjs。 它是 MUI 样式背后的底层系统。

但简而言之,回答你的问题;

  const StyledButton = styled(Button)` 
  &.MuiButton-root { //this targets any class that is added to the main component [1]
    width: 500px;
  }

  .MuiButton-label { //in css-in-js this is effectively '& .MuiButton-label [2]
    color: ${props => props.labelColor};
    justify-content: center;
  }

[1] 针对组件上的主要类

<StyledButton className='test bob'>  << this element is targeted
</StyledButton>

[2] 通过 class 或元素类型定位子元素。 注意 & 和实际 class 之间的空格。

<StyledButton className='test bob'> 
  <span className='MuiButton-label'>test</span> << this element is targeted instead
</StyledButton>

也可以直接使用元素标签

  span { 
    color: ${props => props.labelColor};
    justify-content: center;
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM