样式组件中的比较语句
Comparative statements in styled components
这是一般查询。
在正常的 CSS 中,我们可以这样写:
.container > div {
width: 100%;
flex: 1;
display: flex;
align-items: center;
justify-content: center;
}
但是如何在使用样式组件库的同时实现相同的代码?
要定位容器组件的直接子 div 元素,您需要使用 ${Container} > & {}
来定义这些样式。下面是一个示例,我根据 div 是否是 Container 组件的直接子项为颜色、字体大小、弹性和宽度设置单独的样式。
// Define the Container element styles
const Container = styled.div`
font-size: 16px;
`;
// Define the ChildDiv element styles
const ChildDiv = styled.div`
width: 50%;
flex: 2;
font-size: .5em;
color: green;
${Container} > & {
width: 100%;
flex: 1;
display: flex;
align-items: center;
justify-content: center;
font-size: 2em;
color: purple;
}
`;
// Render components
render(
<Container>
<ChildDiv>
This div is an immediate child of Container
<ChildDiv>
This div is NOT an immediate child of Container
</ChildDiv>
</ChildDiv>
</Container>
);
这是一般查询。 在正常的 CSS 中,我们可以这样写:
.container > div {
width: 100%;
flex: 1;
display: flex;
align-items: center;
justify-content: center;
}
但是如何在使用样式组件库的同时实现相同的代码?
要定位容器组件的直接子 div 元素,您需要使用 ${Container} > & {}
来定义这些样式。下面是一个示例,我根据 div 是否是 Container 组件的直接子项为颜色、字体大小、弹性和宽度设置单独的样式。
// Define the Container element styles
const Container = styled.div`
font-size: 16px;
`;
// Define the ChildDiv element styles
const ChildDiv = styled.div`
width: 50%;
flex: 2;
font-size: .5em;
color: green;
${Container} > & {
width: 100%;
flex: 1;
display: flex;
align-items: center;
justify-content: center;
font-size: 2em;
color: purple;
}
`;
// Render components
render(
<Container>
<ChildDiv>
This div is an immediate child of Container
<ChildDiv>
This div is NOT an immediate child of Container
</ChildDiv>
</ChildDiv>
</Container>
);