如何使用 React Js 更改 SASS 变量值?

Nik*_*til 4 sass reactjs

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

\n\n

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

\n\n

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

\n\n

我的反应代码

\n\n
import React from \'react\';\nimport \'./App.scss\';\n\nclass App extends React.Component {\n    render() {\n        return (\n            <div className="Home">\n                I\xe2\x80\x99m slow and smooth\n                <button onClick={() => console.log()}>Change theme</button>\n            </div>\n        );  \n    }\n}\n\nexport default App;\n
Run Code Online (Sandbox Code Playgroud)\n\n

我的SASS代码:

\n\n
$theme: light;  // I want to control this variable\n\n$bgcolor: #222222;\n\n@if($theme== light) {\n    $bgcolor: white;    \n}\n@else {\n    $bgcolor: black;    \n}\n\n.Home {\n    background-color: $bgcolor;\n    height: 100vh;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

Yuu*_*ari 7

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

:root {
    --app-primaryColor: #f49ad1;
    --app-secondaryColor: #211f1e;
}
Run Code Online (Sandbox Code Playgroud)

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

.button {
    background-color: var(--app-primaryColor);
    color: var(--app-secondaryColor);
}
Run Code Online (Sandbox Code Playgroud)

并使用 React 更新它们

document.documentElement.style.setProperty('--app-primaryColor', '#ffae00')
Run Code Online (Sandbox Code Playgroud)

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

// 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
    })
}
Run Code Online (Sandbox Code Playgroud)