我在文档和其他地方读到&
引用了";回到主";其内部的样式化组件。例如,在本例中,它指的是MyDiv
,当div悬停时,div的文本将变为红色:
const MyDiv = styled.div`
&:hover { color: red; }
`
文档还说,当不存在与号时,CSS声明将引用组件的子级,然而,我注意到,特别是对于像:hover
这样的伪类,如果我省略了与号,行为仍然是一样的。例如,对于下面的代码,我认为hover
只适用于子Text
跨度,但如果您只将div悬停在跨度中,那么跨度中的文本仍然会变为红色
const MyDiv = styled.div`
:hover { color: red; }
// these other style declarations are provided just to help
// illustrate what happens if you want to try this in a code editor:
color: blue;
border: 1px solid black;
width: 100%;
padding: 10px;
`
const Text = styled.span`
border: 1px solid blue;
`
export default App() {
render(
<MyDiv>
<Text>Hello world</Text>
</MyDiv>
)
}
如果有人能帮我澄清一下,我将不胜感激!
在您的代码示例中:
const MyDiv = styled.div`
:hover { color: red; }
// these other style declarations are provided just to help
// illustrate what happens if you want to try this in a code editor:
color: blue;
border: 1px solid black;
width: 100%;
padding: 10px;
`
const Text = styled.span`
border: 1px solid blue;
// --> inherits text color of parent
`
export default App() {
render(
<MyDiv>
<Text>Hello world</Text>
</MyDiv>
)
}
Text
组件或span
从其父元素div
继承颜色样式。
CSS选择器
选择器 | 示例 | 示例描述 |
---|---|---|
.class1元素 | .name1 p | 选择名称为name1 |
元素元素 | div p | 选择