问题
I'm trying to slowly introduce Styled-Components into my existing codebase which relies heavily on global SASS variables (partials imported into a main.scss
).
How do I reference the SCSS variables? The following doesn't work:
import React from 'react';
import styled from 'styled-components';
const Button = styled.button`
background-color: $color-blue;
`;
export default Button;
Am I approaching this from the wrong way?
回答1:
Variables play a very important role in .scss
or .sass
, but the functionality cannot be extended outside the file.
Instead, you have to create a separate .js
file (For example: variable.js) and define all your variables as an object.
回答2:
I wrote up an article about solving this very issue. https://medium.com/styled-components/getting-sassy-with-sass-styled-theme-9a375cfb78e8
Essentially, you can use the excellent sass-extract library along with sass-extract-loader and the sass-extract-js plugin to bring your global Sass variables into your app as a theme object.
回答3:
Pardon me if this is an old question but I thought I chip in on how I use CSS variables for both my .scss
and styled-components
when the need arises.
Basic Usage:
Declaring a global variable (preferably at _variables.scss
)
:root {
--primary-color: #fec85b;
}
Using the global property:
.button {
background-color: var(--primary-color);
}
or
const Button = styled.button`
background-color: var(--primary-color);
`;
Please pay attention to the double line --
.
回答4:
I recommend using the ThemeProvider component. I'm also moving away from sass and towards styled components. The Theming with styled-components uses React's context api and is quite nice. Check out the this documentation Styled Components Theming.
来源:https://stackoverflow.com/questions/49199750/migrating-to-styled-components-with-global-sass-variables-in-react