Reactjs 关于将样式化组件与材质ui混合的问题

Reactjs 关于将样式化组件与材质ui混合的问题,reactjs,material-ui,styled-components,Reactjs,Material Ui,Styled Components,你好,我是一个新手,对造型也不熟悉:) 我正在尝试用样式化的组件对材质ui按钮组件进行样式化 我通过覆盖全局类名来实现这一点,我知道MaterialUI引入了全局类名,如MuiButton root等 我不清楚如何在父选择器中使用“&”,例如: const StyledButton = styled(Button)` &.MuiButton-root { width: 500px; } .MuiButton-label { color: ${props =&

你好,我是一个新手,对造型也不熟悉:) 我正在尝试用样式化的组件对材质ui按钮组件进行样式化

我通过覆盖全局类名来实现这一点,我知道MaterialUI引入了全局类名,如MuiButton root等

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

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

  .MuiButton-label {
    color: ${props => props.labelColor};
    justify-content: center;
  }
`;
上述代码起作用,可实现以下功能:

  • 按钮的宽度为500px
  • 标签的颜色为红色(labelColor作为道具传入)
  • 有关完整代码,请参见下面的沙盒
问题: 为什么我需要MuiButton根的“&”选择器,而对于MuiButton标签我不需要

这也是使用样式化组件设置材质ui样式的最佳方法吗


请参阅下面的沙盒:

使用“&”选择器以类和相邻元素/类为目标。看看cssinjs。这是梅艳芳造型背后的基本系统

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

  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>

“&”选择器用于将类和相邻元素/类作为目标。看看cssinjs。这是梅艳芳造型背后的基本系统

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

  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>