React(css module)

37 阅读1分钟

css module 存在的意义

  • 因为React没有scoped 而React项目又是SPA(单页面应用), 所以需要一种方式 来解决css的样式冲突,也就是把每个组件的样式做成单独的作用域。
  • css module 就是一种实现方式

安装依赖

npm install less -D # 安装less 任选其一
npm install sass -D # 安装sass 任选其一
npm install stylus -D # 安装stylus 任选其一

在vite中使用css module

  1. 在vite中,css module是开箱即用的。
  • 只需要把配置css的文件名改为 xxx.module.css/less/sass/stylus
  • 在要使用的页面文件中引入,import xxx from './xxx.module.css'
  • 标签中使用方式为 className = 'xxx.类名'
  1. 示例:
  • src/components/Button/index.module.less
.button {
  color: red;
}
  • src/components/Button/index.tsx
//使用方法,直接引入即可
import styles from './index.module.less';

export default function Button() {
  return <button className={styles.button}>按钮</button>;
}

  • 编译结果
  • React通过css module把样式类名编译为
<button class="button_pmkzx_6">按钮</button>
  • 就是在每个类名后面加上哈希值 使他变得唯一 以作区分 实现样式隔离

维持类名

在css module中 不希望某个类名被编译为带有哈希值的类名 希望可以全局使用该类名 那么我们可以这样实现

.app {
  background: red;
  width: 200px;
  height: 200px;
  :global(.button) {
    background: blue;
    width: 100px;
    height: 100px;
  }
}
//在使用的时候,就可以直接使用原始的类名 button
import styles from './index.module.scss';
const App: React.FC = () => {
  return (
    <>
      <div className={styles.app}>
        <button className='button'>按钮</button>
      </div>
    </>
  );
}

React.FC是一个工具 快速方便的为函数组件提供类型推导 FC:FunctionComponent