我目前正在使用React和Material UI构建一个项目。我试图通过按钮将主题类型从浅色切换为深色,但没有成功。
我需要使用useEffect挂钩吗? Codesandbox:https://codesandbox.io/s/stack-overflow-dark-theme-light-theme-xh0s4
答案 0 :(得分:0)
您的主题没有改变,因为您没有修改状态。
首先,您需要有两个主题:明暗。
import { createMuiTheme } from "@material-ui/core/styles";
const baseTheme = {palette: {
primary: {
main: "#FF0000",
light: "#E7F6E7",
contrastText: "#FFFFFF"
},
secondary: {
main: "#FFFFFF"
},
}};
export const lightTheme = createMuiTheme({palette: {...baseTheme.palette, type: 'light'}});
export const darkTheme = createMuiTheme({palette: {...baseTheme.palette, type:'dark'}});
然后您将根据组件状态渲染主题:
import React from "react";
import { lightTheme, darkTheme } from "./theme";
import { ThemeProvider } from "@material-ui/core/styles";
import Navbar from "./components/Navbar";
import Landing from "./components/Landing";
import "./index.css";
import CssBaseline from "@material-ui/core/CssBaseline";
function App() {
const [isLightTheme, setIsLightTheme] = React.useState(true);
const toggleTheme = () => {
setIsLightTheme(!isLightTheme);
};
return (
<ThemeProvider theme={isLightTheme ? lightTheme : darkTheme}>
<CssBaseline />
<Navbar theme={isLightTheme ? lightTheme : darkTheme} handleToggleTheme={() => toggleTheme()} />
<div className="container">
<Landing />
</div>
</ThemeProvider>
);
}
export default App;