首页 > 解决方案 > 如何使用 React Js 更改 SASS 变量值?

问题描述

在制作重复问题之前,请确保您阅读了我的问题

我在 2019 年问这个问题,其中 React Js 文档指定我们可以在我们的反应项目中使用 SASS 这里的链接

我想使用由用户单击控制的动态变量在浅色主题和深色主题之间切换

我的反应代码

import React from 'react';
import './App.scss';

class App extends React.Component {
    render() {
        return (
            <div className="Home">
                I’m slow and smooth
                <button onClick={() => console.log()}>Change theme</button>
            </div>
        );  
    }
}

export default App;

我的 SASS 代码:

$theme: light;  // I want to control this variable

$bgcolor: #222222;

@if($theme== light) {
    $bgcolor: white;    
}
@else {
    $bgcolor: black;    
}

.Home {
    background-color: $bgcolor;
    height: 100vh;
}

标签: reactjssass

解决方案


如果您仍然感兴趣,您可以通过使用css 变量来更改 sass 变量

:root {
    --app-primaryColor: #f49ad1;
    --app-secondaryColor: #211f1e;
}

然后在你的 scss 文件中使用这些变量

.button {
    background-color: var(--app-primaryColor);
    color: var(--app-secondaryColor);
}

并使用 React 更新它们

document.documentElement.style.setProperty('--app-primaryColor', '#ffae00')

这是使用 react 和 redux 的(几乎)完整示例。一个setTheme动作用于从文档根元素更新颜色。这样你也可以直接从你的 react 根标签 props 配置你的主题。这些道具将被设置为初始状态。

// index.html
<div
    id="app"
    primaryColor="red"
    secondaryColor="#f2f2f2"
/>

// css-variables.scss
:root {
    --app-primaryColor: #f49ad1;
    --app-secondaryColor: #211f1e;
}

// app.module.scss
.button {
    background-color: var(--app-primaryColor);
    color: var(--app-secondaryColor);
}

// index.js
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'

import './css-variables'

import App from './app'
import configureStore from './configureStore'

const rootElement = document.getElementById('app')

//Here you could extract your theme variables from your rootElement props and set it as an initial redux state
const initialProps = {}
const store = configureStore(initialProps)

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
rootElement)

// app.js
import React from 'react'
import { connect } from 'react-redux'

import { setTheme } from './actions'
import styles from './app.module'

class App extends React.Component {
    componentDidMount() {
        //In case you have an initial state set from your rootElement
        const { theme, setTheme } = this.props
        setTheme(theme)
    }
    
    generateTheme() {
        const primaryColors = ['#ffae00', '#f49ad1', '#d0666b', '#7c6cd0', '#6cd09d', '#d0ba6c']
        const secondaryColors = ['#4c4c4e', '#2f2f2f', '#dcdcdc', '#fff']

        return {
            primaryColor: primaryColors[Math.floor(Math.random() * primaryColors.length)]
            secondaryColor: secondaryColors[Math.floor(Math.random() * secondaryColors.length)]
        }
    }

    onButtonClick() {
        const theme = this.generateTheme()
        this.props.setTheme(theme)
    }

    render() {
        return (
            <div className="{styles.button}" onClick={this.onButtonClick.bind(this)}>
                Change theme
            </div>
        )
    }
}

const mapStateToProps = (state) => ({
    theme: state.theme,
})

export default connect(mapStateToProps, { setTheme })(App)

// actions.js
export const setTheme = theme => dispatch => {
    //You change your theme vars directly from the root element
    Object.keys(theme)
        .filter(prop => typeof theme[prop] !== 'undefined' && theme[prop] !== null)
        .forEach(prop => document.documentElement.style.setProperty(`--app-${prop}`, theme[prop]))
    
    dispatch({
        type: 'THEME/SET',
        payload: theme
    })
}

推荐阅读