简体   繁体   中英

How to use joint selectors in styled-component

I have legacy CSS which looks like this:

.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.

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?


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%;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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