【React】React CSS 样式设置全攻略

在 React 中设置 CSS 样式主要有以下几种方式,各有适用场景:

1. 内联样式 (Inline Styles)

直接在 JSX 元素中使用 style 属性,值为 JavaScript 对象(使用驼峰命名法)

jsx 复制代码
function Component() {
  return (
    <div style={{ 
      color: 'red', 
      backgroundColor: 'lightblue',
      padding: '10px',
      borderRadius: '5px' // 注意驼峰命名
    }}>
      内联样式示例
    </div>
  );
}

2. 外部样式表 (External CSS)

创建独立的 .css 文件,通过 import 引入

css 复制代码
/* styles.css */
.container {
  padding: 20px;
  border: 1px solid #ccc;
  margin: 10px;
}
jsx 复制代码
import './styles.css'; // 引入样式文件

function Component() {
  return <div className="container">外部样式表示例</div>;
}

3. CSS Modules (推荐)

使用 [name].module.css 命名约定,实现局部作用域

css 复制代码
/* Component.module.css */
.error { 
  color: red;
  font-weight: bold;
}
jsx 复制代码
import styles from './Component.module.css'; // 自动生成唯一类名

function Component() {
  return <div className={styles.error}>CSS Modules 示例</div>;
}

4. CSS-in-JS 库 (如 styled-components)

通过 JavaScript 直接编写 CSS

bash 复制代码
npm install styled-components  # 先安装
jsx 复制代码
import styled from 'styled-components';

// 创建带样式的组件
const StyledButton = styled.button`
  background: ${props => props.primary ? 'blue' : 'white'};
  color: ${props => props.primary ? 'white' : 'blue'};
  padding: 10px 20px;
  border-radius: 4px;
`;

function Component() {
  return (
    <>
      <StyledButton>普通按钮</StyledButton>
      <StyledButton primary>主按钮</StyledButton>
    </>
  );
}

5. 动态样式 (根据状态变化)

结合状态管理和样式设置

jsx 复制代码
function DynamicComponent() {
  const [isActive, setIsActive] = useState(false);

  // 动态类名
  const buttonClasses = `btn ${isActive ? 'btn-active' : ''}`;
  
  // 动态内联样式
  const divStyle = {
    transform: isActive ? 'scale(1.1)' : 'none',
    transition: 'transform 0.3s'
  };

  return (
    <div>
      <div style={divStyle}>动态缩放元素</div>
      <button 
        className={buttonClasses}
        onClick={() => setIsActive(!isActive)}
      >
        {isActive ? '激活中' : '未激活'}
      </button>
    </div>
  );
}

最佳实践建议:

  1. 组件级样式 → 首选 CSS Modules 或 CSS-in-JS
  2. 全局主题/基础样式 → 使用外部样式表
  3. 简单动态样式 → 内联样式或动态类名
  4. 复杂交互/主题 → CSS-in-JS 解决方案

常见问题解决:

类名冲突 → 使用 CSS Modules 自动生成唯一类名
伪类/媒体查询 → 避免用内联样式(使用 CSS/CSS-in-JS)
全局样式污染 → 为根元素添加命名空间
动态主题切换 → 考虑使用 CSS 变量或 ThemeProvider (CSS-in-JS)

根据项目规模和团队偏好选择合适的方式,中小型项目推荐 CSS Modules + 少量内联样式,大型项目可考虑 CSS-in-JS 方案。

相关推荐
牛奶1 小时前
2026年大模型怎么选?前端人实用对比
前端·人工智能·ai编程
牛奶1 小时前
前端人为什么要学AI?
前端·人工智能·ai编程
Kagol4 小时前
🎉OpenTiny NEXT-SDK 重磅发布:四步把你的前端应用变成智能应用!
前端·开源·agent
GIS之路5 小时前
ArcGIS Pro 中的 notebook 初识
前端
JavaGuide5 小时前
7 道 RAG 基础概念知识点/面试题总结
前端·后端
ssshooter5 小时前
看完就懂 useSyncExternalStore
前端·javascript·react.js
格砸6 小时前
从入门到辞职|从ChatGPT到OpenClaw,跟上智能时代的进化
前端·人工智能·后端
Live000007 小时前
在鸿蒙中使用 Repeat 渲染嵌套列表,修改内层列表的一个元素,页面不会更新
前端·javascript·react native
柳杉7 小时前
使用Ai从零开发智慧水利态势感知大屏(开源)
前端·javascript·数据可视化