我在 React 应用程序中遇到主题切换问题。该应用程序支持两个主题,我将其称为主题一和主题二。我使用延迟加载根据所选主题动态加载相应的主题组件。
每个主题都为公共按钮类定义了自己的样式。例如,在主题一中,按钮为红色,而在主题二中,按钮为棕色。
当我使用按钮切换主题时就会出现问题。最初,当从主题一转换到主题二时,按钮颜色正确地从红色更新为棕色。然而,切换回主题一后,按钮颜色未能按预期恢复为红色。后续的主题切换也不会反映按钮颜色的任何变化。
这是我的代码结构的简化版本:
// App.js
import React, { useState, Suspense } from 'react';
import ThemeContext from './ThemeContext';
import './App.css';
export const MawbThemeContext = createContext({ theme: "" })
const ThemeOne = React.lazy(() => import('./ThemeOne'));
const ThemeTwo = React.lazy(() => import('./ThemeTwo'));
const App = () => {
const [theme, setTheme] = useState('one');
const handleChangeTheme = () => {
startTransition(() => {
if (theme === 'one') {
setTheme('two');
} else {
setTheme('one');
}
});
};
return (
<ThemeContext.Provider value={{ theme, handleChangeTheme }}>
<Suspense fallback={<div>Loading...</div>}>
{theme === 'one' ? <ThemeOne /> : <ThemeTwo />}
</Suspense>
</ThemeContext.Provider>
);
};
export default App;
// ThemeOne.js
import React, { useContext } from 'react';
import ThemeContext from './ThemeContext';
import './ThemeOne.css';
const ThemeOne = () => {
const { handleChangeTheme } = useContext(ThemeContext);
return (
<>
<button className="common-btn-one" onClick={handleChangeTheme}>
Theme One Button
</button>
</>
);
};
export default ThemeOne;
// ThemeTwo.js
import React, { useContext } from 'react';
import ThemeContext from './ThemeContext';
import './ThemeTwo.css';
const ThemeTwo = () => {
const { handleChangeTheme } = useContext(ThemeContext);
return (
<>
<button className="common-btn-two" onClick={handleChangeTheme}>
Theme Two Button
</button>
</>
);
};
export default ThemeTwo;
这里的问题是:如果你想改变一个通用按钮的主题,你真的需要两个不同的组件吗?我建议您只创建一个按钮组件,并仅更改该按钮的主题:
//App.jsx
import { useState } from "react"
import Button from './components/Button'
import ThemeContext from "./context/ThemeContext"
function App() {
const [theme, setTheme] = useState("light")
const value = { theme, setTheme }
return (
<div className="App">
<ThemeContext.Provider value={value}>
<Button />
</ThemeContext.Provider>
</div>
)
}
export default App
//ThemeContext.js
import React from "react"
const ThemeContext = React.createContext({
theme: "light",
setTheme: () => {},
})
export default ThemeContext
import { useContext } from "react"
import ThemeContext from "../context/ThemeContext.js"
const Button = () => {
const { theme, setTheme } = useContext(ThemeContext)
return (
<button
onClick={() => setTheme(theme == "dark" ? "light" : "dark")}
style={{backgroundColor: theme === "dark" ? "red" : "white"}}
>
Change theme
</button>
)
}
export default Button;
希望这可以帮助你!祝你好运!