reactjs - 如何根据 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);
解决方案
所以我相信会有人在寻找这个问题的答案,因为它可以为用户提供更改应用颜色模式的能力。我的解决方案如下,如果我遇到任何问题,我会更新它。
在 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"
}
}
});
}
如果您对此有任何建议以使其变得更好,仍然非常感谢。
推荐阅读
- python - 使用 SQLAlchemy 连接来自多个表的数据
- java - 即使在成功编译后运行包含另一个 Java 类的文件时出现“找不到符号错误”
- python - 我如何分隔字符串中的某些单独的东西
- php - 通过键值从另一个数组生成数组
- reactjs - 使用带有 typescript 和 material-ui 的 react-hook-form 来显示错误消息的正确方法
- phpstorm - 无法在 PhpStorm 设置中更改 JavaScript 代码样式
- flutter - Flutter:使用带有 PopupMenuButton 的选择功能导航到另一个页面
- shell - 顶部没有显示完整的命令行 -c
- reactjs - 在 useEffect 中不使用异步效果时,无法对未安装的组件执行 React 状态更新
- javascript - 单击图库图像时,导航栏会自动滚动