2017-04-19 61 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

主题