如何在样式组件中使用联合选择器
How to use joint selectors in styled-component
我有旧版 CSS,它看起来像这样:
.btn_1 {
color: #fff;
background: #004dda;
display: inline-block;
}
.btn_1:hover {
background-color: #FFC107;
color: #222 !important;
}
.btn_1.full-width {
display: block;
width: 100%;
}
我想迁移到在 React 中使用样式化组件(CSS-in-JS 样式)。
到目前为止,这是我的迁移:
.btn_1 {
color: #fff;
background: #004dda;
display: inline-block;
:hover {
background-color: #FFC107;
color: #222 !important;
}
}
但是对于像 .btn_1.full-width
这样的选择器,样式组件中是否有任何解决方案,或者我应该为此创建另一个 CSS 块?
我认为做这样(或更好)的事情会很酷:
.btn_1 {
${this}.full-width {
display: block;
width: 100%;
}
}
但我似乎无法在文档中找到解决方案。你知道这是怎么可能的吗?这甚至是个好主意吗?
您可以使用 & 符号来链接嵌套选择器。
.btn_1 {
&.full-width {
display: block;
width: 100%;
}
}
来自 official styled components documentation
对于复杂的选择器模式,可以使用与号 (&) 来回指主要组件。以下是其潜在用途的更多示例:
const Thing = styled.div.attrs({ tabIndex: 0 })`
color: blue;
&:hover {
color: red; // <Thing> when hovered
}
& ~ & {
background: tomato; // <Thing> as a sibling of <Thing>, but maybe not directly next to it
}
& + & {
background: lime; // <Thing> next to <Thing>
}
&.something {
background: orange; // <Thing> tagged with an additional CSS class ".something"
}
.something-else & {
border: 1px solid; // <Thing> inside another element labeled ".something-else"
}
`
我有旧版 CSS,它看起来像这样:
.btn_1 {
color: #fff;
background: #004dda;
display: inline-block;
}
.btn_1:hover {
background-color: #FFC107;
color: #222 !important;
}
.btn_1.full-width {
display: block;
width: 100%;
}
我想迁移到在 React 中使用样式化组件(CSS-in-JS 样式)。
到目前为止,这是我的迁移:
.btn_1 {
color: #fff;
background: #004dda;
display: inline-block;
:hover {
background-color: #FFC107;
color: #222 !important;
}
}
但是对于像 .btn_1.full-width
这样的选择器,样式组件中是否有任何解决方案,或者我应该为此创建另一个 CSS 块?
我认为做这样(或更好)的事情会很酷:
.btn_1 {
${this}.full-width {
display: block;
width: 100%;
}
}
但我似乎无法在文档中找到解决方案。你知道这是怎么可能的吗?这甚至是个好主意吗?
您可以使用 & 符号来链接嵌套选择器。
.btn_1 {
&.full-width {
display: block;
width: 100%;
}
}
来自 official styled components documentation
对于复杂的选择器模式,可以使用与号 (&) 来回指主要组件。以下是其潜在用途的更多示例:
const Thing = styled.div.attrs({ tabIndex: 0 })`
color: blue;
&:hover {
color: red; // <Thing> when hovered
}
& ~ & {
background: tomato; // <Thing> as a sibling of <Thing>, but maybe not directly next to it
}
& + & {
background: lime; // <Thing> next to <Thing>
}
&.something {
background: orange; // <Thing> tagged with an additional CSS class ".something"
}
.something-else & {
border: 1px solid; // <Thing> inside another element labeled ".something-else"
}
`