首页 > 解决方案 > 样式组件中的比较语句

问题描述

它是一个一般查询。在普通的 CSS 中,我们可以这样写:

.container > div {
    width: 100%;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
}

但是如何在使用样式组件库时实现相同的代码?

标签: cssstyled-components

解决方案


要定位 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>
);

推荐阅读