react module.scss 避免全局冲突类似vue中scoped

创建 index.module.scss 文件

复制代码
src/
  components/
    MyComponent/
      index.module.scss
      index.tsx

2. 编写 index.module.scss 内容

复制代码
// src/components/MyComponent/index.module.scss

.container {
  padding: 20px;
  background-color: #f0f0f0;

  .title {
    font-size: 24px;
    color: #333;
  }

  .button {
    background-color: #007bff;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 5px;

    &:hover {
      background-color: #0056b3;
    }
  }
}

在 React 组件中使用 index.module.scss

复制代码
import React from 'react';
import styles from './index.module.scss'; // 引入样式文件

const MyComponent: React.FC = () => {
  return (
    <div className={styles.container}>
      <h1 className={styles.title}>Hello, World!</h1>
      <button className={styles.button}>Click Me</button>
    </div>
  );
};

export default MyComponent;

CSS 模块化的优势

  • 局部作用域:样式只作用于当前组件,不会影响其他组件。
  • 避免命名冲突:CSS 模块会自动生成唯一的类名,避免全局样式冲突。
  • 支持 SCSS 语法:可以使用嵌套、变量、混合等 SCSS 特性。

如果需要根据条件动态添加类名,可以使用模板字符串或 classnames 库

复制代码
import React from 'react';
import styles from './index.module.scss';
import classNames from 'classnames'; // 引入 classnames 库

const MyComponent: React.FC<{ isActive: boolean }> = ({ isActive }) => {
  return (
    <div
      className={classNames(styles.container, {
        [styles.active]: isActive, // 根据条件添加类名
      })}
    >
      <h1 className={styles.title}>Hello, World!</h1>
      <button className={styles.button}>Click Me</button>
    </div>
  );
};

export default MyComponent;
相关推荐
代码煮茶7 小时前
React 组件封装方法论 —— 以 Todo App 为例
javascript·react.js
猩猩程序员13 小时前
零基础学习 React 19
react.js
假如让我当三天老蒯15 小时前
Options API(选项式 API) 和 Composition API(组合式 API)
前端·vue.js·面试
spmcor15 小时前
React 进阶指南:状态管理进化——从 Context 到 Redux Toolkit(第五篇)
react.js
spmcor15 小时前
React 进阶指南:React Router v6 完全实战(第四篇)
react.js
用户800391387831 天前
工程化 SCSS 排错新思路|Gemini 一键解析语法、变量、层级编译问题
scss
YFF菲菲兔1 天前
调度系统和调和系统的桥梁
react.js
YFF菲菲兔2 天前
commitRoot 源码解析
react.js
光影少年3 天前
react批量更新、同步/异步更新场景
前端·react.js·掘金·金石计划
YFF菲菲兔3 天前
completeRoot 源码解析
react.js