Skip to content

样式 in React

CSS 模块, 样式-组件, Tailwind, and 选择样式方法.

你将学到

  • 主要样式方法 in React
  • CSS 模块 for scoped, traditional CSS
  • CSS-in-JS 使用样式-组件
  • Utility-首先 CSS 使用 Tailwind

概念讲解

Styling Approaches

React does not prescribe a styling solution — there are several popular approaches, each with trade-offs. Plain CSS / CSS classes (via className) is the simplest: you write CSS files and apply class names. CSS Modules scope class names automatically to avoid collisions. CSS-in-JS libraries like styled-components and Emotion let you write CSS inside JavaScript with full access to props and theme. Utility-first frameworks like Tailwind CSS provide small, composable utility classes. The best choice depends on your team, project size, and preferences.

CSS Modules

CSS Modules are CSS files where class names are locally scoped by default. You import a CSS file as 样式 and apply classes as className={样式.card}. The build tool generates unique class names (like card_abc123), preventing collisions between components. This gives you the familiarity of plain CSS with the safety of scoping. CSS Modules work great with component-based architecture — each component has its own .module.css file.

CSS-in-JS (styled-components)

styled-components lets you define styled elements using tagged template literals: const Button = styled.buttoncolor: ${props => props.primary ? "blue" : "gray"};``. Styles are scoped to the component, can adapt based on props, and support theming via a ThemeProvider. The styles are generated at runtime (or extracted at build time with some setups). This approach keeps styles co-located with the component and enables dynamic styling based on props, but adds runtime overhead and can make debugging harder.

Utility-First (Tailwind CSS)

Tailwind CSS provides low-level utility classes like flex, p-4, 文本-lg, bg-blue-500 that you compose directly in your JSX: className="flex p-4 bg-blue-500 文本-white rounded". This approach eliminates the need to name things and switch between CSS and JSX files. It produces small, optimized CSS bundles (only the classes you use are included). The trade-off is that className strings can get long, and there is a learning curve for the utility class names. Tailwind is increasingly the most popular choice for new React projects.

示例代码

              // Approach 1: CSS Modules — scoped, traditional CSS
import styles from "./Button.module.css";
function ButtonA({ label }) {
  return <button className={styles.primary}>{label}</button>;
}

// Approach 2: styled-components — CSS-in-JS with dynamic props
import styled from "styled-components";
const StyledButton = styled.button`
  padding: 8px 16px;
  border-radius: 4px;
  background: ${props => props.primary ? "#3b82f6" : "#6b7280"};
  color: white;
  font-size: 14px;
  cursor: pointer;
  &:hover { opacity: 0.9; }
`;
function ButtonB({ label, primary }) {
  return <StyledButton primary={primary}>{label}</StyledButton>;
}

// Approach 3: Tailwind CSS — utility classes composed in JSX
function ButtonC({ label, primary }) {
  return (
    <button className={`
      px-4 py-2 rounded text-sm text-white cursor-pointer
      hover:opacity-90 transition-opacity
      ${primary ? "bg-blue-500" : "bg-gray-500"}
    `}>
      {label}
    </button>
  );
}
            

Three 方法到 相同 button: CSS 模块 for scoped CSS, 样式-组件 for 动态 CSS-in-JS, and Tailwind for utility-类 composition. 每个有 不同 trade-offs.

动手试一试

常见错误

错误写法

Using inline 样式 for 一切相反的 类

正确做法

Inline 样式 (样式={{}}) cannot use pseudo-类, media 查询, or animations. Use className 使用 CSS files, CSS 模块, or Tailwind for 任何事超出简单 one-off 样式.

错误写法

创建 overly 长 Tailwind 类字符串那个是 困难到 读取

正确做法

Extract repeated 类 combinations 到 reusable 组件 or use Tailwind's @apply directive in CSS file. Keep className 字符串 readable 通过分组 related utilities and using multi-行 template literals.

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误