Реагирование Изменение пользовательского интерфейса материала - PullRequest
0 голосов
/ 25 апреля 2019

Не могли бы вы помочь мне динамически изменить тему пользовательского интерфейса React Material.

https://imgur.com/S8zsRPQ https://imgur.com/Ul8J40N

Я пытался изменить свойства темы по нажатию кнопки.Свойства темы изменяются, как показано в консоли.Но изменение не отражается на теме.

Код песочницы: https://codesandbox.io/s/30qwyk92kq

const themeChange = () => {
  alert(theme);
  theme.palette.type = "light";
  console.log(theme);
};
ReactDOM.render(
  <MuiThemeProvider theme={theme}>
    <React.Fragment>
      <CssBaseline />
      <App changeTheme={themeChange} />
    </React.Fragment>
  </MuiThemeProvider>,
  document.getElementById("app")
);

Когда я нажимаю кнопку, тема должна измениться на Темный цвет

1 Ответ

0 голосов
/ 27 апреля 2019

В вашем коде тип темы изменен. Но страница не перерисовывается с новой темой.

Я изменил код в index.js и App.js следующим образом. Попробуйте этот подход. Это работает.

index.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

ReactDOM.render(
  <App/>,
  document.getElementById("app")
);

App.js

import React from "react";
import CssBaseline from "@material-ui/core/CssBaseline";
import Typography from "@material-ui/core/Typography";
import { Button } from "@material-ui/core";
import { MuiThemeProvider, createMuiTheme } from "@material-ui/core/styles";
import blueGrey from "@material-ui/core/colors/blueGrey";
import lightGreen from "@material-ui/core/colors/lightGreen";

class App extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      themeType : 'dark',
    }
  }

  changeTheme(){
    if (this.state.themeType == 'dark'){
      this.setState({themeType:'light'});
    } else {
      this.setState({themeType:'dark'});
    }
  }
  render() {
    let theme = createMuiTheme({
      palette: {
        primary: {
          light: lightGreen[300],
          main: lightGreen[500],
          dark: lightGreen[700]
        },
        secondary: {
          light: blueGrey[300],
          main: blueGrey[500],
          dark: blueGrey[700]
        },
        type: this.state.themeType
      }
    });
    return (
      <MuiThemeProvider theme={theme}>
        <CssBaseline />
        <Typography>Hi there!</Typography>
        <Button
          variant="contained"
          color="secondary"
          onClick={()=>{this.changeTheme()}}
        >
          Change
        </Button>
      </MuiThemeProvider>
    );
  }
}
export default App;
...