阅读(4200) (2)

styled-components 安装

2020-07-24 11:55:58 更新

安装

从 npm 安装 styled-components :

npm install --save styled-components
强烈推荐使用 styled-components 的 babel 插件 (当然这不是必须的).它提供了许多益处,比如更清晰的类名,SSR 兼容性,更小的包等等.

如果没有使用模块管理工具或者包管理工具,也可以使用官方托管在 unpkg CDN 上的构建版本.只需在HTML文件底部添加以下<script>标签:

<script src="https://unpkg.com/styled-components/dist/styled-components.min.js" rel="external nofollow" ></script>

添加 styled-components 之后就可以访问全局的 window.styled 变量.

const Component = window.styled.div`
  color: red;
`
注意这用使用方式需要页面在 styled-components script 之前引入 react CDN bundles

入门

styled-components 通过标记的模板字符来设置组件样式.

它移除了组件和样式之间的映射.当我们通过styled-components定义样式时,我们实际上是创建了一个附加了样式的常规 React 组件.

以下的例子创建了两个简单的附加了样式的组件, 一个Wrapper和一个Title:

// 创建一个 Title 组件,它将渲染一个附加了样式的 <h1> 标签
const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

// 创建一个 Wrapper 组件,它将渲染一个附加了样式的 <section> 标签
const Wrapper = styled.section`
  padding: 4em;
  background: papayawhip;
`;

// 就像使用常规 React 组件一样使用 Title 和 Wrapper 
render(
  <Wrapper>
    <Title>
      Hello World!
    </Title>
  </Wrapper>
);
注意styled-components 会为我们自动创建 CSS 前缀