我有旧版 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 block ?
我认为做这样的事情(或更好)会很酷:
.btn_1 {
${this}.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"
}
`
关于reactjs - 如何在样式组件中使用联合选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54684871/