有可能改变scss变量吗?

时间:2018-03-29 19:33:13

标签: reactjs

是否可以在react中覆盖scss变量。我有一个带有一些scss变量的theme.scss。是否可以使用Container的props更改这些scss变量。我知道我可以将style={{ backgroundColor: style.backgroundColor }}更改为style={{ backgroundColor: this.props.backgroundColor }},但$primary-font-color不会更改,因为我在我的theme.scss中设置了$primary-font-color: $item-color;。是否可以覆盖我的scss变量$item-color以便$primary-font-color也改变?

这只是一些示例代码来解释我的意思:

theme.scss

$background-color: white;
$item-color: gray;
$primary-font-color: $item-color; // I want to override $item-color so that also $primary-font-color changes
$secondary-font-color: darken($primary-font-color, 15%);

export: {
 backgroundColor: $background-color;
 itemColor: $item-color;
 primaryFontColor: $primary-fonty-color;
 secondaryFontColor: $secondary-font-color;
}

index.js

    ReactDOM.render(
      <Container 
        backgroundColor: 'gray,
        itemColor: 'black'  // I want to change my scss variable to this value
       />,
      document.getElementById('root')
    );

容器

import style from '../style/_theme.scss';

class Container extends Component {
  render(){

  <div style={{ backgroundColor: style.backgroundColor }} >
    <div className='item' style={{ backgroundColor: style.itemColor }} >
      <p style={{ backgroundColor: style.itemColor }} >Some Text.. </p>
  </div>
  </div>

}

1 个答案:

答案 0 :(得分:3)

正如我在评论中所说的,用React操纵CSS(SCSS等)通常不是一个好主意,因为它将变得难以维护。执行此操作的首选方法是使用类,因为它们可重用且更易读。

在您的情况下,您可以做的是定义不同的主题类,例如:

.whiteTheme {
    .backgroundColor {
       color: white;
    }
    .itemColor {
       color: white;
    }
    .primaryFontColor {
       color: white;
    }
}


.greyTheme {
    .backgroundColor {
       color: black;
    }
    .itemColor {
       color: grey;
    }
    .primaryFontColor {
       color: grey;
    }
}

然后使用React操作主题类名称(这可能只发生一次,或者每个组件,如果你需要它):

class Container extends Component {

  render() {
    <div className={this.props.isWhiteTheme ? 'whiteTheme' : 'greyTheme'}>
      <div style="backgroundColor">
        <div className='item' style="itemColor">
          <p style="primaryFontColor">Some Text.. </p>
        </div>
      </div>
    </div>
  }
}

P.S命名道具或CSS类backgroundColor是不可取的,它只是为了大方向。