有了样式化组件,为什么伪类在没有与符的情况下仍然可以工作



我在文档和其他地方读到&引用了";回到主";其内部的样式化组件。例如,在本例中,它指的是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选择器

的元素内的所有<p>元素选择<div>元素内的所有<p>元素
选择器示例示例描述
.class1元素.name1 p选择名称为name1
元素元素div p

相关内容

最新更新