问题
I cannot find better solution for theming. I have a sass-file with variables:
vars.scss:
$colors: (
dark: (
theme1: #0096dc,
theme2: #eb8200,
…
),
…
);
For now I pass theme
prop to all components which should have some styling depending on which page user is viewing. In React I build classname like this:
<div className={styles[`button${theme ? `-${theme}` : ``}`]}>{children}</div>
and in sass I do:
@import 'vars';
.button{
/* basic styles */
font-size: 14px;
border: 1px solid;
@each $theme, $color in map-get($colors, dark) {
&-#{$theme} {
@extend .button;
border-color: $color;
color: $color;
}
}
}
But this is absolutely inconvenient, because I need to place such code every time I need to style element depending on theme.
There are solutions how to load different files with variables for theming in webpack, but I receive theme
prop from redux, so webpack doesn't have access to that prop.
As well as, I cannot find solution to pass property from react component to sass. Only opposite.
No way to use variables in imports in sass. Still not implemented.
Unfortunately, Cannot use CSS-in-JS approach in current project.
Please help to find better approach.
回答1:
I would make it a stateless functional component.
function BrightBox(props){
<div className={styles[`button${theme ? `-${theme}` : ``}`]}>
{props.children}
</div>
}
Then import it and use it. There is no need to pass theme around.
{user.notice ?
<BrightBox>
there are {user.notice.issues.size} outstanding issues!
</BrightBox>
: null
}
来源:https://stackoverflow.com/questions/42388393/react-component-theme-using-sass-variables-depending-on-react-prop-value