2017-04-19 28 views
6

我使用styled-components來構建我的組件。接受自定義值的所有樣式屬性都會在我的組件中重用(因爲它應該是)。考慮到這一點,我想使用某種全局變量,以便更新將傳播到所有組件,而無需單獨更新每個樣式。使用帶有風格元件的Javascript變量

事情是這樣的:

// Variables.js 

var fontSizeMedium = 16px; 

// Section.js 

const Section = styled.section` 
    font-size: ${fontSizeMedium}; 
`; 

// Button.js 

const Button = styled.button` 
    font-size: ${fontSizeMedium}; 
`; 

// Label.js 

const Label = styled.span` 
    font-size: ${fontSizeMedium}; 
`; 

我想我得到的語法錯的?另外,我知道Javascript地不推薦使用全局變量,但在設計中,跨組件的土地重用風格是絕對必要的。這裏的折衷是什麼?

回答

10

我終於明白了這一點,所以這裏是你如何做到這一點,至少如果使用React。

您需要在一個文件中定義變量並導出它們。

// Variables.js 

export const FONTSIZE_5 = '20px'; 

然後您需要將這些變量導入到每個組件文件中。

// Button.js 

import * as palette from './Variables.js'; 

然後你可以使用你的風格組件中的變量是這樣的:

const Button = styled.button` 
    font-size: ${palette.FONTSIZE_5}; 
`; 
4

纏繞你的應用程序<ThemeProvider>可以幫助:

https://www.styled-components.com/docs/advanced#theming

const theme = { 
    fontColour: 'purple' 
} 

render() { 
    return (
    <ThemeProvider theme={theme}> 
     <MyApplication /> 
    </ThemeProvider> 
) 
} 

那將給所有兒童風格的組件訪問主題,如下所示:

const MyApplication = styled.section` 
    color: ${props => props.theme.fontColour} 
` 

或者

const MyFancyButton = styled.button` 
    background: ${props => props.theme.fontColour} 
` 

或訪問通過https://www.styled-components.com/docs/advanced#getting-the-theme-without-styled-components

主題