React 组件不会多次重新渲染

时间:2021-05-07 08:00:18

标签: javascript reactjs

我正在制作一个应用程序,其中有一个按钮可以将组件的主题从暗更改为亮。我的应用程序第一次运行正常,但在第二次尝试时不起作用

例如:如果我第一次点击按钮,它会将主题更改为暗模式,但是当我想将主题更改为亮模式时,它不起作用

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>
  );
   }
   }

我为此使用了材质 ui

1 个答案:

答案 0 :(得分:0)

我不知道为什么它只改变了一次。但是您可以通过在每次渲染时创建 theme 来修复。

首先创建函数createTheme

const createTheme = (isDark) =>
  createMuiTheme({
    palette: {
      type: isDark ? "dark" : "light",
    },
  });

然后,像这样更新 ThemeProvider

<ThemeProvider theme={createTheme(this.state.switch)}>