如何在样式中使用兄弟选择器 css

how to use sibling selector css in styled

我有一个样式化的组件,它看起来像:

import styled from 'styled-components';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';

export const CategoryList = styled(List)`
`;
//this is what i want to change
export const CategoryListItem = styled(ListItem)`
  border-top: 2px solid #f4f4f4;
`;

export const CategoryListItemText = styled(ListItemText)`
  padding-left: 5px;
`;

export const ListItemHeading = styled(ListItem)`
  background-color: #f4f4f4;
`;

在这种情况下如何使用兄弟姐妹 & + & ?

我想实现类似的目标:

li + li {
border-top: 1px solid red;
}

我怎样才能做到这一点?

这与 SCSS 中的方法相同 &:

export const CategoryListItem = styled(ListItem)`
  border-top: 2px solid #f4f4f4;

  & + & { // this will work for <CategoryListItem /><CategoryListItem />
    border-top: 1px solid red;
  }
`;

您也可以使用 html 元素设置样式,但上面的代码是更好的做法

& + li { // this will work for <CategoryListItem /><li />
  border-top: 1px solid red;
}

基本上你可以用&

做任何嵌套
& li { // this will work for <CategoryListItem><li /></CategoryListItem>
}
& li.test { // this will work for <CategoryListItem><li class="test" /></CategoryListItem>
}

您可以在官方文档中阅读: https://styled-components.com/docs/basics#pseudoelements-pseudoselectors-and-nesting