将Javascript变量与样式组件一起使用
作者:互联网
我正在使用styled-components来构建我的组件.接受自定义值的所有样式属性都会在我的组件中重复使用(应该如此).考虑到这一点,我想使用某种全局变量,以便更新将传播到所有组件,而无需单独更新每个样式.
像这样的东西:
// 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领域不推荐全局变量,但在设计中,组件之间的重用样式是绝对必要的.这里的权衡是什么?
解决方法:
包装< 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访问主题
标签:javascript,styled-components 来源: https://codeday.me/bug/20191004/1853351.html