Skip to content

styled-components

css in js 作为组件使用

js
import React from 'react';
import styled from 'styled-components';

const Button = styled.button`
  padding: 8px 16px;
  background-color: #0070f3;
  color: white;
  border-radius: 4px;
  border: none;
  cursor: pointer;

  &:hover {
    background-color: #005bb5;
  }
`;
export default function App() {
  return <Button>Click me</Button>;
}
特性CSS ModulesStyled Components
样式定义单独 CSS 文件 .module.cssJavaScript 模板字符串
作用域默认局部作用域自动 scoped,内联样式
动态样式支持不支持,需通过类名切换实现直接使用 JS 变量和条件
书写习惯纯 CSSCSS-in-JS
依赖仅构建工具支持需安装 styled-components 库
体积无额外运行时依赖有运行时开销