2017-03-02 23 views
0

我試圖製作一個應用程序外部的反應組件庫。這將是一個npm模塊,加載Webpack。我正在使用CSS模塊來設計組件,我正在嘗試瞭解如何使其某些屬性可定製。例如,背景顏色。使用React和CSS模塊/ PostCSS製作可自定義的CSS屬性

我想用CSS變量這有比如這個語法在CSS文件:

.myClass { 
    backgrond-color: var(--backgroundColor, red); 
} 

--backgroundColor是一個變量我可以設置和紅色是默認。我的問題是,有沒有辦法從.jsx文件加載時將變量傳遞給.css文件?所以我可以將一個變量對象傳遞給組件,這會影響它如何加載它的樣式?我可以使用PostCSS嗎?

謝謝。

PS:我知道這可以通過使用內聯JS風格來解決,但我想先給CSS一個鏡頭。

回答

0

你不能注入javascript到一個css文件和PostCSS只能轉換你的css文件,但不能注入/替換變量。

然而,這樣做的一種方式是創建具有默認變量的.scss(sass)文件,例如, $background-color: red;然後,您可以將您的模塊和.scss文件導入到其.scss文件中,並根據自己的變量覆蓋像$background-color這樣的任何變量(如果他們願意的話)。

+0

你能指點我一個這樣的例子嗎? –

+1

@PabloBarríaUrenda請檢查這個帖子:http://stackoverflow.com/questions/17089717/how-to-overwrite-scss-variables-when-compiling-to-css。但是,我沒有一個實例來指出。你應該檢查bootstrap或其他框架是如何做的(它們允許設置變量)。 –

0

我不知道我理解你的權利,但在這裏我所想的:

當你需要.css文件用的WebPack它增加了這個CSS作爲一個字符串背後頁面<head>元素現場。

爲什麼你不用Webpack使用自己的函數來做什麼,就像這樣。

您的模塊:

import $ from 'jquery'; 
 

 
/* this function builds string like this: 
 
    :root { 
 
     --bg: green; 
 
     --fontSize: 25px; 
 
    } 
 

 
    from the options object like this: 
 
    { 
 
     bg: 'green', 
 
     fontSize: '25px' 
 
    } 
 
*/ 
 
function buildCssString(options) { 
 
    let str = ':root {\n' 
 
    
 
    for(let key in options) { 
 
     str += '\t--' + key + ': ' + options[key] + ';\n' 
 
    } 
 

 
    str += '}'; 
 

 
    return str; 
 
} 
 

 
/* this function adds css string to head element */ 
 
export const configureCssVariables = function(options) { 
 
    $(function() { 
 
     var $head = $('head'), 
 
      $style = $('<style></style>'); 
 

 
     $style.text(buildCssString(options)); 
 
     $style.appendTo($head) 
 
    }); 
 
}

用法:

import {configureCssVariables} from './your-module'; 
 

 
configureCssVariables({ 
 
    bg: 'green', 
 
    fontSize: '25px' 
 
});

而且你的CSS是簡單

/* default variables that will be overwritten 
 
    by calling configureCssVariables() 
 
*/ 
 
:root { 
 
    --bg: yellow; 
 
    --fontSize: 16px; 
 
} 
 

 
.myClass { 
 
    backgrond-color: var(--bg); 
 
    font-size: var(--fontSize); 
 
}

0

它可以通過在您的管道中添加PostCSS和postcss-custom-properties插件來實現。它有一個variables選項,它會將JS定義的變量(屬性)注入到任何正在處理的文件中。
這消除了每個CSS模塊文件中的任何東西@import的需要。

const theme = { 
    'color-primary': 'green', 
    'color-secondary': 'blue', 
    'color-danger': 'red', 
    'color-gray': '#ccc', 
}; 

require('postcss-custom-properties')({ 
    variables: theme, 
}); 

瞭解如何與babel-plugin-css-modules-transformhttps://github.com/pascalduez/react-module-boilerplate/blob/master/src/theme/index.jshttps://github.com/pascalduez/react-module-boilerplate/blob/master/.babelrc#L21使用它,但隨着的WebPack工作爲好。

+0

我的問題是(這可能是我的一個架構問題)是這些組件已經構建,作爲外部包使用。他們的CSS已經編譯好了,所以使用自定義屬性將無法工作。 –