React component theme using sass variables depending on React prop value

旧巷老猫 提交于 2020-01-05 04:31:12

问题


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

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