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

你好,我也是新手,也是样式的新手:) 我正在尝试使用样式化组件来样式化Material-ui Button组件

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

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

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

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

上面的代码有效,并且可以实现以下目的:

  • 按钮的宽度为500px
  • 标签为红色(labelColor作为属性传递)
  • 请参见下面的沙箱以获取完整代码

问题: 为什么我不需要MuiButton根的“&”选择器,而不需要MuiButton根的标签?

这也是用样式化组件样式化Material-ui的最佳方法吗?

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

yanlovey 回答:有关将样式化的组件与material-ui混合的问题

“&”选择器用于定位类和相邻元素/类。看看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>

您也可以直接使用element标签

  span { 
    color: ${props => props.labelColor};
    justify-content: center;
  }
本文链接:https://www.f2er.com/3162427.html

大家都在问