简体   繁体   中英

styled-components: using `& + &` selector and adapt based on props

I have some components rendered with the same styled-component, and I want to make some margin-top between them

const Item = styled.div`
  color: ${props => props.active ? 'red' : '#333'};
  & + & {
    margin-top: 10px;
  }
`

<Item active={false}/>
<Item active={false}/>
<Item active={false}/>

so far so good,

but when one of them has a true active prop, the margin-top is missing, I found that is because <Item active={false}/> and <Item active={true} /> do not have the same class name.

Is there a way to fix this issue?

PS

I'm just get started with styled-components, and I'm also looking for best practice with it.

the components should have the same class name as they are using the same styled-components component.

But regarding the & + & , if you want all of them, then just plain margin-top: 10px is enough, if you want to do on in between, you can just specify the first-child, last-child to be margin: 0 .

<React.Fragment>
  <Item active={false}>First</Item>
  <Item active={false}>Second</Item>
  <Item active={false}>Third</Item>
</React.Fragment>

A codesandbox for demo: https://codesandbox.io/s/62l02knn5r

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