首页 > 解决方案 > 如何根据 Redux Store 条目加载 Material UI Theme

问题描述

我将以下文件作为我的应用程序加载时加载的第一个文件。我想从我的 Redux 商店中提取调色板类型,就像this.props.pageTheme当我触发对主题的更改时,它会发生在整个应用程序中。虽然当我进入时type: this.props.pageTheme我得到一个错误说TypeError: Cannot read property 'props' of undefined..这是有道理的,因为商店不是在 const 启动时生成的。但是..那么,我怎样才能阅读商店中的内容并在页面上进行更改?我已经看到了诸如创建多个主题 const 并根据this.props.getTheme应用程序的返回应用它的解决方案,但这样做的方式太丑陋了。有没有什么聪明的方法来处理主题值注入到 createMuiTheme 中?

import React, { Component } from "react";
import { MuiThemeProvider, createMuiTheme } from "@material-ui/core/styles";

const theme = createMuiTheme({
  palette: {
    type: "light",
  }
});

class App extends Component {
  render() {
      return (
        <MuiThemeProvider theme={theme}>
          <>page content</>
        </MuiThemeProvider>
      );
    }
  }
}

function mapStateToProps(state) {
  return {
    pageTheme: state.Page.Theme
  };
}

export default connect(
  mapStateToProps
)(App);

标签: reactjsmaterial-ui

解决方案


所以我相信会有人在寻找这个问题的答案,因为它可以为用户提供更改应用颜色模式的能力。我的解决方案如下,如果我遇到任何问题,我会更新它。

在 Redux Store 我有:

const initialState = {
  Page: {
    Theme: "light"
  },
};

在主 App.js 文件中,我有

<MuiThemeProvider theme={theme(this.props.pageTheme)}>

作为我在页面上的内容的包装。

我有以下主题功能

function theme(mode) {
  return createMuiTheme({
    palette: {
      type: mode,
      primary: {
        light: "#757ce8",
        main: "#3f50b5",
        dark: "#002884",
        contrastText: "#fff"
      },
      secondary: {
        light: "#ff7961",
        main: "#f44336",
        dark: "#ba000d",
        contrastText: "#000"
      }
    }
  });
}

如果您对此有任何建议以使其变得更好,仍然非常感谢。


推荐阅读