css - 样式组件中的比较语句
问题描述
它是一个一般查询。在普通的 CSS 中,我们可以这样写:
.container > div {
width: 100%;
flex: 1;
display: flex;
align-items: center;
justify-content: center;
}
但是如何在使用样式组件库时实现相同的代码?
解决方案
要定位 Container 组件的直接子 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>
);
推荐阅读
- jquery - 从总分钟数计算年份,同时考虑闰年
- sql - 如何显示不同列中两个值组合的倒数第二个日期
- apache-flink - 输出中存在重复键
- amazon - 如何在不注册 Associate Program 的情况下获取 Amazon 产品信息?
- mysql - 出现语法错误,但非常不确定出了什么问题
- c - 如何在没有 strstr 函数的情况下更改此代码?
- mysql - MySQL解析\u0080以上的字符
- asp.net-core - ASP.NET Core 2.0 - 用户在一小时内注销
- java - 通过 JDBC URL 使用 TestContainers DB 但使用 @Rule 时出错
- python - Tweepy 搜索查询问题