跳至主要內容

新增 CSS 模組樣式表

請注意:此功能可在 react-scripts@2.0.0 以上版本使用。

此專案同時支援 CSS 模組 和一般樣式表,使用 [name].module.css 檔案命名規範。CSS 模組允許透過自動產生 [filename]\_[classname]\_\_[hash] 格式的獨特類別名稱來設定 CSS 範圍。

提示:如果要使用 Sass 預處理樣式表,請確認遵循 安裝說明,然後將樣式表檔案副檔名變更如下:[name].module.scss[name].module.sass

有了 CSS 模組,您可以在不同的檔案中使用同一個 CSS 類別名稱,而不用擔心名稱衝突。在此深入了解 CSS 模組 詳細資訊

Button.module.css

.error {
background-color: red;
}

another-stylesheet.css

.error {
color: red;
}

Button.js

import React, { Component } from 'react';
import styles from './Button.module.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet

class Button extends Component {
render() {
// reference as a js object
return <button className={styles.error}>Error Button</button>;
}
}

結果

與其他 .error 類別名稱無衝突

<!-- This button has red background but not red text -->
<button class="Button_error_ax7yz">Error Button</button>

這是一個選用功能。一般的 <link> 樣式表和 CSS 檔案能完全支援。CSS 模組啟用於以 .module.css 副檔名結尾的檔案。