gpt4 book ai didi

javascript - 如何在 react 中动态更改配置文件中的值?

转载 作者:行者123 更新时间:2023-11-29 22:46:52 25 4
gpt4 key购买 nike

我有一个包含 config.js 文件的模板,该文件加载主题配置我想添加从浅色模式到深色模式的切换开关。当您在 config.js 中进行更改时主题会更改,但我不知道如何动态更改 config.js 中的值。

我计划在索引文件中进行切换。

配置.js

export default {
defaultPath: '/dashboard/default',
basename: '',
layout: 'vertical',
preLayout: '',
collapseMenu: false,
layoutType: 'dark', // menu-light
navIconColor: true,
headerBackColor: 'header-default', // header-dark
navBackColor: 'navbar-dark', // navbar-dark
navBrandColor: 'brand-dark', // brand-dark
navBackImage: false,
rtlLayout: false,
navFixedLayout: true,
headerFixedLayout: false,
boxLayout: false,
navDropdownIcon: 'style1',
navListIcon: 'style1',
navActiveListColor: 'active-*', // active-dark
navListTitleColor: 'title-default', // title-dark
navListTitleHide: false,
configBlock: false,
layout6Background : 'linear-gradient(to right, #A445B2 0%, #D41872 52%, #FF0066 100%)',
layout6BackSize : '',
};

索引.js

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import {Provider} from 'react-redux';
import {BrowserRouter} from 'react-router-dom';

import App from './App/index';
import * as serviceWorker from './serviceWorker';
import reducer from './store/reducer';
import config from './config';

const store = createStore(reducer);

const app = (
<Provider store={store}>
<BrowserRouter basename={config.basename}>
{/* basename="/datta-able" */}
<App />
</BrowserRouter>
</Provider>
);

ReactDOM.render(app, document.getElementById('root'));

最佳答案

您可以通过 using the state hook 完成它.这是一个示例(您可以在此处查看我的代码:https://codesandbox.io/s/thirsty-keller-cjqb8):

// put this in config.js
const initialConfig = {
darkMode: true
};

const App = () => {
// dark mode is initally true, because we used the config value as inital value for darkMode
const [darkMode, setDarkMode] = useState(initialConfig.darkMode);

// change handler that is invoked when we change the value of the checkbox
const changeMode = ({ currentTarget: { checked } }) => setDarkMode(checked);

return (
// use className based on the value of darkMode
<div className={darkMode ? "darkMode" : ""}>
<label>
<input checked={darkMode} type="checkbox" onChange={changeMode} />
use dark mode
</label>
</div>
);
};

我使用配置作为初始值。但是,您需要一个状态来存储当前处于事件状态的模式的信息。

关于javascript - 如何在 react 中动态更改配置文件中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58210518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com