[英]React component is not re-rendering multiple time
I am making an application in which i have a button which change the theme from dark to light of the component.我正在制作一个应用程序,其中我有一个按钮,可以将组件的主题从深色更改为浅色。 my application works fine for the first time but it does not work on second attempt
我的应用程序第一次运行良好,但在第二次尝试时无法运行
for example: If i click the button first time then it will change the theme to the dark mode but when i want to change the theme into light mode then it does not work例如:如果我第一次单击按钮,那么它会将主题更改为暗模式,但是当我想将主题更改为亮模式时,它不起作用
import {
Button,
createMuiTheme,
Grid,
Paper,
Switch,
ThemeProvider,
Typography,
} from "@material-ui/core";
import React, { Component } from "react";
export default class Mode extends Component {
constructor(props) {
super(props);
this.state = {
switch: false,
};
this.darkTheme = createMuiTheme({
palette: {
type: "dark",
},
});
this.lightTheme = createMuiTheme({
palette: {
type: "light",
},
});
}
componentDidUpdate() {
console.log(this.state.switch);
}
render() {
return (
<div>
<ThemeProvider
theme={this.state.switch === true ? this.darkTheme : this.lightTheme}
> // <-- **Condition for changing the mode**
<Paper style={{ height: "100vh" }}>
<Grid container direction="column">
<Typography variant="h1">this is my app</Typography>
<Button variant="contained" color="primary">
A button
</Button>
<Button variant="contained" color="secondary">
Another button
</Button>
<Switch
checked={this.state.switch}
onChange={() =>
this.setState((prev) => ({ switch: !prev.switch }))
}
name="Dark Mode"
inputProps={{ "aria-label": "secondary checkbox" }}
/>
</Grid>
</Paper>
</ThemeProvider>
</div>
);
}
}
I am using material ui for this我为此使用了材料 ui
I'm not sure why it changes only one time.我不知道为什么它只改变一次。 But you can fix by create
theme
every render.但是您可以通过每次渲染创建
theme
来修复。
First, create function createTheme
:首先,创建 function
createTheme
:
const createTheme = (isDark) =>
createMuiTheme({
palette: {
type: isDark ? "dark" : "light",
},
});
Then, update ThemeProvider
like this:然后,像这样更新
ThemeProvider
:
<ThemeProvider theme={createTheme(this.state.switch)}>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.