LadyZhong 2019-06-29
官方文档地址: https://www.styled-components.com/
中文文档地址:https://github.com/hengg/styled-components-docs-zh
styled-components是一个React的第三方库,是CSS in JS的优秀实践。
初次了解styled-components是在读林昊翻译的React设计模式与最佳实践一书时。虽然接触的比较晚,但深深的被它的强大和优雅所吸引。然而其中文资料比较匮乏,为帮助更多的小伙伴了解这个强大的工具,翻译了部分官方文档。能力所限,已翻译部分可能仍有字词错误或语句不通顺的地方,欢迎有能力的同学帮助纠正。
styled-components究竟强在哪里?这要从它所解决的问题说起:
不可否认,CSS是一门神奇的“语言”(What kind of language is CSS?)。
它易于上手、却难以精通。它没有变量、函数等概念导致它的表现力要稍弱于其它语言,而它索要解决的问题却又很复杂。 关于这一点,为什么 CSS 这么难学?这个问题下的一百多个答案就很能说明问题了。
日常使用中,CSS 的痛点很多,但大多围绕以下两点:
随着组件化时代的来临,前端应用开始从组件的层面对 CSS 进行封装:也就是通过 JS 来声明、抽象样式从而提高组件的可维护性;在组件加载时动态的加载样式,动态生成类名从而避免全局污染。
styled-components就是其中的佼佼者。
顾名思义,styled-components以组件的形式来声明样式,让样式也成为组件从而分离逻辑组件与展示组件(这个思路看起来是不是很眼熟),来看一下官方的示例:
const Button = styled.a`
  /* This renders the buttons above... Edit me! */
  display: inline-block;
  border-radius: 3px;
  padding: 0.5rem 0;
  margin: 0.5rem 1rem;
  width: 11rem;
  background: transparent;
  color: white;
  border: 2px solid white;
  /* The GitHub button is a primary button
   * edit this to target it specifically! */
  ${props => props.primary && css`
    background: white;
    color: palevioletred;
  `}
`
render(
  <div>
    <Button
      href="https://github.com/styled-components/styled-components"
      target="_blank"
      rel="noopener"
      primary
    >
      GitHub
    </Button>
    <Button as={Link} href="/docs" prefetch>
      Documentation
    </Button>
  </div>
)可以看到,styled-components通过标记的模板字符来设置组件样式.
它移除了组件和样式之间的映射.当我们通过styled-components定义样式时,我们实际上是创建了一个附加了样式的常规 React 组件.
同时它支持将props以插值的方式传递给组件,以调整组件样式.
官方宣称styled-components的优点如下:
CSS 的问题,也有其他解决方案,比如著名的CSS Module方案。社区中也一直存在对于两者孰优孰劣的争执。
本文不会比较这两种解决方案,但有兴趣的朋友可以参考一下这两篇文章:
background-color: blue;background-color: yellow;<input type="button" value="变蓝" @click="changeColorT