styled-components:使用 `& + &` 选择器并根据 props 进行调整

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

我有一些组件使用相同的样式组件渲染,我想在它们之间做一些 margin-top

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

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

到目前为止一切顺利,

但是当其中一个有 true active prop 时,margin-top 丢失了,我发现这是因为 <Item active={false}/><Item active={true} /> 没有相同的 class名字.

有办法解决这个问题吗?

P.S.

我刚刚开始使用样式组件,我也在寻找最佳实践。

组件应具有相同的 class 名称,因为它们使用相同的 styled-components 组件。

但是关于& + &,如果你想要所有的,那么简单的margin-top: 10px就足够了,如果你想在两者之间做,你可以指定first-child, last-childmargin: 0.

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

用于演示的 codesandbox:https://codesandbox.io/s/62l02knn5r