样式

React 提供了多种方式来为组件添加样式。你可以选择最适合你项目的方式。

样式方案

1. 内联样式

内联样式直接在 JSX 中指定,使用 camelCase 属性名。

function Component() {
  const style = {
    color: 'white',
    backgroundColor: 'blue',
    padding: '10px'
  };

  return <div style={style}>Styled Component</div>;
}

2. CSS 类名

使用 className 属性添加 CSS 类。这是最传统和简单的方式。

/* styles.css */
.primary-button {
  background-color: blue;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
}

// Component.js
import './styles.css';

function Button() {
  return <button className="primary-button">Click me</button>;
}

3. CSS Modules

CSS Modules 可以避免类名冲突,每个组件的样式都是局部作用域的。

/* Button.module.css */
.button {
  background-color: blue;
  color: white;
  padding: 10px 20px;
}

// Button.js
import styles from './Button.module.css';

function Button() {
  return <button className={styles.button}>Click me</button>;
}

4. CSS-in-JS

使用 styled-components 或 emotion 等库在 JavaScript 中编写样式。

import styled from 'styled-components';

const StyledButton = styled.button`
  background-color: blue;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
`;

function Button() {
  return <StyledButton>Click me</StyledButton>;
}

5. Tailwind CSS

Tailwind CSS 提供了实用类,可以快速构建界面。

function Button() {
  return (
    <button className="bg-blue-500 text-white px-5 py-2 rounded">
      Click me
    </button>
  );
}

选择合适的样式方案

  • 小型项目:内联样式或 CSS 类名
  • 中型项目:CSS Modules
  • 大型项目:CSS-in-JS 或 Tailwind CSS
  • 设计系统:Tailwind CSS 或 CSS-in-JS

最佳实践

  • 保持样式的一致性
  • 避免内联样式用于复杂布局
  • 使用 CSS 变量管理主题
  • 考虑样式的可维护性和性能

下一步

学习样式后,继续了解组件基础