reactjs - 如何在样式组件中使用联合选择器

标签 reactjs css styled-components

我有旧版 CSS,如下所示:

.btn_1 {
    color: #fff;
    background: #004dda;
    display: inline-block;
}
.btn_1:hover {
  background-color: #FFC107;
  color: #222 !important;
}
.btn_1.full-width {
  display: block;
  width: 100%;
}

我想迁移到在 React 中使用样式组件(CSS-in-JS 样式)。

这是我迄今为止的迁移:

.btn_1 {
    color: #fff;
    background: #004dda;
    display: inline-block;
    :hover {
        background-color: #FFC107;
        color: #222 !important;
    }
}

但是样式组件中有没有针对 .btn_1.full-width 这样的选择器的解决方案,或者我应该为此创建另一个 CSS block ?

<小时/>

我认为做这样的事情(或更好)会很酷:

.btn_1 {
    ${this}.full-width {
        display: block;
        width: 100%;
   }
}

但我似乎无法在文档中找到解决方案。您知道这是怎么可能的吗?或者这是一个好主意吗?

最佳答案

来自 official styled components documentation

对于复杂的选择器模式,可以使用与号 (&) 来引用主要组件。以下是其潜在用途的更多示例:

const Thing = styled.div.attrs({ tabIndex: 0 })`
  color: blue;

  &:hover {
    color: red; // <Thing> when hovered
  }

  & ~ & {
    background: tomato; // <Thing> as a sibling of <Thing>, but maybe not directly next to it
  }

  & + & {
    background: lime; // <Thing> next to <Thing>
  }

  &.something {
    background: orange; // <Thing> tagged with an additional CSS class ".something"
  }

  .something-else & {
    border: 1px solid; // <Thing> inside another element labeled ".something-else"
  }
`

关于reactjs - 如何在样式组件中使用联合选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54684871/

相关文章:

javascript - 单击显示/隐藏 - Javascript

javascript - 向表格行添加光晕

css - 我无法使用样式组件将 Button 组件在 Material-UI 中居中

javascript - react-native-testing-library 和 styled-components 无法访问 Prop

css - 将普通 CSS "style"与 Bootstrap "class"混合使用是好习惯吗?

javascript - 加载时不显示数据 - 仅在页面刷新后显示

javascript - 为什么数组中的两个对象中只有一个作为 prop 传递?

reactjs - 带有大括号中的参数的函数式 React 组件

html - 使用&符号返回父选择器?

css - NavLink 仅在单击时更改按钮颜色但不进行设置