我有一个样式化的组件,它看起来像:
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;
`;
在这种情况下如何使用 sibling & + & ?
我想实现这样的目标:
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
关于javascript - 如何在样式中使用同级选择器 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59757602/