1. 程式人生 > 其它 >CSS Modules

CSS Modules

今天我們就把CSS Modules是個啥子東西給他弄明白,這樣會更加分。
首先我們來看一張圖:
一張圖理解 CSS Modules 的工作原理:

我們自己編碼的時候有倆個檔案,一個是ProductList.less檔案,一個是ProductList.jsx檔案
在構建之後會將less檔案轉換成藍色標題的那個檔案。

可以由此看出:

button class在構建之後會被重新命名為ProductList_button_1FU0u。button是local name,而 ProductList_button_1FU0u 是 global name 。你可以用簡短的描述性名字,而不需要關心命名衝突問題。
然後你要做的全部事情就是在 css/less 檔案裡寫 .button {…},並在元件裡通過 styles.button 來引用他。

定義全域性CSS
CSS Modules預設是區域性作用域的,想要聲名一個全域性規則,可用:global語法。

比如:

.title {
color: red;
}
:global(.title) {
color: green;
}

在引用的時候:

<App className={styles.title} /> // red
<App className="title" /> // green

classnames Package
在一些複雜場景中,一個元素可能對應多個className,而每個className又基於一些條件來決定是否出現。這時,classnames這個庫就非常有用。

import classnames from 'classnames';
const App = (props) => {
const cls = classnames({
btn: true,
btnLarge: props.type === 'submit',
btnSmall: props.type === 'edit',
});
return <div className={ cls } />;
}
這樣,傳入不同的 type 給 App 元件,就會返回不同的 className 組合:

<App type="submit" /> // btn btnLarge
<App type="edit" /> // btn btnSmall


本文來自部落格園,作者:喆星高照,轉載請註明原文連結:https://www.cnblogs.com/houxianzhou/p/15479296.html