styled-components

464 阅读1分钟

styled-components 是一个 css in js 类库。和所有同类型的类库一样,通过 js 赋能解决了原生 css 所不具备的能力,比如变量、循环、函数等。诸如 sass&less 等预处理可以解决部分 css 的局限性。

同时,Styled-components就是为React而生的,以往我们想要做到css scope都需要在webpack中各种配置,或者使用js的解决方案。 而styled-components你只需要import styled from 'styled-components';即可。

安装

  1. $ yarn add styled-components
  2. TS声明:$ yarn add --dev @types/styled-components

例子

import React from 'react';

import styled from 'styled-components';

// Create a <Title> react component that renders an <h1> which is
// centered, palevioletred and sized at 1.5em
const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

// Create a <Wrapper> react component that renders a <section> with
// some padding and a papayawhip background
const Wrapper = styled.section`
  padding: 4em;
  background: papayawhip;
`;

// Use them like any other React component – except they're styled!
<Wrapper>
  <Title>Hello World, this is my first styled component!</Title>
</Wrapper>

继承

// The Button from the last section without the interpolations
const Button = styled.button`
  color: palevioletred;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`;
// A new component based on Button, but with some override styles
const TomatoButton = styled(Button)`  //这里就是继承
  color: tomato;
  border-color: tomato;
`;
render(
  <div>
    <Button>Normal Button</Button>
    <TomatoButton>Tomato Button</TomatoButton>
  </div>
);

总结

  1. 提出了 container 和 components 的概念,移除了组件和样式之间的映射关系,符合关注度分离的模式。
  2. 样式写在 js 文件里,降低 js 对 css 文件的依赖。
  3. 支持组件之间继承,方便代码复用,提升可维护性。
  4. 不用再担心样式命名的问题。