Using Javascript Variables with styled-components

让人想犯罪 __ 提交于 2019-11-30 03:18:59

I eventually figured this out, so here's how you can do it, at least if using React.

You need to define the variables in one file and export them.

// Variables.js

export const FONTSIZE_5 = '20px';

Then you need to import those variables into each component file.

// Button.js

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

Then you can use the variables in your styled-components like this:

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

Wrapping a <ThemeProvider> around your application may help:

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

const theme = {
  fontColour: 'purple'
}

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

That will give all child styled-components access to the theme like so:

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

Or

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

Or access the theme via https://www.styled-components.com/docs/advanced#getting-the-theme-without-styled-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!