简体   繁体   English

如何在样式组件中使用关节选择器

[英]How to use joint selectors in styled-component

I have legacy CSS which looks like this: 我有遗留的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%;
}

I want to migrate to using styled-components (CSS-in-JS style) in React. 我想迁移到在React中使用样式组件(CSS-in-JS样式)。

This is my migration so far: 这是我到目前为止的迁移:

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

but is there any solution in styled-components for selectors like .btn_1.full-width or I should just create another CSS block for that? 但是在.btn_1.full-width选择器的样式组件中是否有任何解决方案,或者我应该为此创建另一个CSS块?


I think it would be cool to do something like this (or better): 我认为做这样(或更好)的事情会很酷:

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

but I can't seem to find the solution in the documents. 但我似乎无法在文件中找到解决方案。 Do you have any idea how this is possible or is this even a good idea? 你知道这是怎么可能的,或者这是一个好主意吗?

from official styled components documentation 来自官方风格的组件文档

For complex selector patterns, the ampersand (&) can be used to refer back to the main component. 对于复杂的选择器模式,可以使用&符号(&)来引用主要组件。 Here are some more examples of its potential usage: 以下是其潜在用法的更多示例:

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"
  }
`

You can use the ampersand to chain nested selectors. 您可以使用&符号链接嵌套选择器。

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

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

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