javascript - 如何在样式中使用同级选择器 css

标签 javascript css reactjs ecmascript-6 styled-components

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

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/

相关文章:

reactjs - 如何更改 Material UI 选项卡按钮的宽度

javascript - 动态组件 onClick 不工作

javascript - Jquery - 如何仅在未拖动链接时运行函数 onclick?

javascript - Chrome 表格因奇怪的 URL 而溢出

css - 滚动在移动设备 (iPhone) 上不起作用

PHP/CSS : Shortcode won't display correctly, 并显示在每个页面的头部(内容之前)

javascript - `useState` ,仅当对象中的值发生变化时更新组件

JavaScript 触发 InputEvent.isTrusted = true

javascript - 获取 3 列中每列动态添加的最低值的总和

html - 没有卷轴的大背景