【问题标题】:Question about mixing styled-components with material-ui关于将 styled-components 与 material-ui 混合的问题
【发布时间】:2020-03-01 09:43:02
【问题描述】:

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

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

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

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

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

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

  • 按钮的宽度为 500 像素
  • 标签颜色为红色(labelColor 作为道具传入)
  • 完整代码请参见下面的沙箱

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

这也是用样式化的组件来设置 material-ui 样式的最佳方式吗?

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

【问题讨论】:

    标签: reactjs material-ui styled-components


    【解决方案1】:

    “&”选择器用于定位类和相邻元素/类。看看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] 通过类或元素类型定位子元素。注意 & 和实际类之间的空格。

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

    也可以直接使用元素标签

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

    【讨论】:

      猜你喜欢
      • 2019-08-02
      • 2018-09-14
      • 2020-05-12
      • 2019-06-27
      • 2020-11-16
      • 2020-01-16
      • 2020-06-28
      • 2021-05-19
      • 2020-05-06
      相关资源
      最近更新 更多