Create-React-App專案中CSS Modules的使用
阿新 • • 發佈:2020-12-26
目錄
一、功能描述
- 實現:
- 版本:
react: ^16.13.1
、node-sass: ^4.14.1
二、程式碼實現
-
啟用SCSS
- 安裝node-sass
npm install node-sass --save
- 更改css檔案字尾及引入
將.css
檔案字尾改為.scss
,在.js
或.jsx
檔案中引入。
import './App.scss';
-
啟用CSS Modules
專案預設支援CSS Modules,需要將模組化的css檔案字尾改為
.module.css
.module.scss
,然後在.js
或.jsx
檔案中引入。
示例程式碼:import React, { Component } from 'react'; import styles from './Button.module.css'; // 引入模組化後的css檔案 import './another-stylesheet.css'; // 引入普通樣式檔案 class Button extends Component { render() { return <button className={styles.error}>Error Button</button>; } }
-
使用多個類名
在不使用CSS Modules時,我們給元素設定多個類名時通常使用
join()
或ES6模板字串
,這裡給出使用CSS Modules時這兩種形式的寫法:// 陣列join()形式 <div className={[styles.menu_bar, styles.active].join(" ")}>Menu</div> // ES6模板字串形式 <div className={`${styles.menu_bar} ${styles.active}`}>Menu</div>
-
動態使用類名
有時需要根據某一個變數的值來動態決定類名,這裡也同樣給出
join()
ES6模板字串
兩種形式的寫法:// 陣列join()形式 <div className={[styles.menu_bar, show?styles.active:''].join(" ")}>Menu</div> // ES6模板字串形式 <div className={`${styles.menu_bar} ${show?styles.active:''}`}>Menu</div>
-
同時使用公共樣式
有時可能同時需要使用公共樣式中的類名,這裡也給出
join()
及ES6模板字串
兩種形式的寫法:// 陣列join()形式 <div className={['red_txt', styles.menu_bar, show?styles.active:''].join(" ")}>Menu</div> // ES6模板字串形式 <div className={`red_txt ${styles.menu_bar} ${show?styles.active:''}`}>Menu</div>