1. 程式人生 > 實用技巧 >Create-React-App專案中CSS Modules的使用

Create-React-App專案中CSS Modules的使用

目錄

1. 功能描述
2. 程式碼實現
3. 參考文件

一、功能描述

二、程式碼實現

  • 啟用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>
    

三、參考文件