【问题标题】:How to convert this into styled-components and how to nest classes如何将其转换为样式组件以及如何嵌套类
【发布时间】:2019-02-19 12:45:49
【问题描述】:

我从 css-in-js 开始,使用 styled-components 作为主库,我有 2 个问题。

第一个问题,如何嵌套类?

footer{
  color: red;
}

footer p{
  padding: 16px 8px;
  font-size: 30px;
}
  <footer>
    <div className="container">
      <p>&copy; 1997-2015,All rights reserved.</p>
    </div>
  </footer>

我的第二个问题是,我有一个使用 2 个类的 div,一个在 container 来自引导程序,另一个是我自己的自定义类,我不知道如何连接这两个类在样式组件中。

【问题讨论】:

标签: javascript css reactjs styled-components


【解决方案1】:
const MyStyledComponent = styled.footer`
  & > div {
    color: red;
  }

  & > div > p {
    padding: 16px 8px;
    font-size: 30px;
  }
`;

将 & 视为“这个元素”。


有两种方法可以将类添加到样式化组件。一种是简单地添加 className 属性

<StyledComponent className="container my-class" />

或者,如果您想在应用程序的每个地方使用这些类,您可以通过设置样式组件的属性来为其设置默认类。

const StyledComponent = styled.div.attrs({
 className: 'container my-class',
})`
  color: #f00;
`;

【讨论】:

    猜你喜欢
    • 2021-01-09
    • 1970-01-01
    • 2021-08-24
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-06
    相关资源
    最近更新 更多