Reactjs 如何基于Redux商店条目加载材质UI主题
我将下面的文件作为应用程序加载时加载的第一个文件。我想从我的Redux商店中提取调色板类型,如Reactjs 如何基于Redux商店条目加载材质UI主题,reactjs,material-ui,Reactjs,Material Ui,我将下面的文件作为应用程序加载时加载的第一个文件。我想从我的Redux商店中提取调色板类型,如this.props.pageTheme,因此当我触发主题更改时,它会在整个应用程序中发生。虽然当我输入type:this.props.pageTheme时,我得到一个错误,说TypeError:cannotread属性“props”为未定义的。。这是有意义的,因为存储不是在常量开始时生成的。但是那么,我如何阅读商店中的内容并在页面上进行更改?我见过一些解决方案,比如创建多个主题常量,并在返回应用程序时
this.props.pageTheme
,因此当我触发主题更改时,它会在整个应用程序中发生。虽然当我输入type:this.props.pageTheme
时,我得到一个错误,说TypeError:cannotread属性“props”为未定义的
。。这是有意义的,因为存储不是在常量开始时生成的。但是那么,我如何阅读商店中的内容并在页面上进行更改?我见过一些解决方案,比如创建多个主题常量,并在返回应用程序时基于this.props.getTheme
应用它,但这是一种非常丑陋的方法。是否有任何聪明的方法来处理主题值注入CreateMuiteme
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);
import React,{Component}来自“React”;
从“@material ui/core/styles”导入{MuiThemeProvider,createMuiTheme}”;
const theme=createMuiTheme({
调色板:{
类型:“轻”,
}
});
类应用程序扩展组件{
render(){
返回(
页面内容
);
}
}
}
函数MapStateTops(状态){
返回{
页面主题:state.Page.Theme
};
}
导出默认连接(
mapStateToProps
)(App);
所以我相信会有人在寻找这个问题的答案,因为它为用户提供了改变应用程序颜色模式的功能。我的解决方案如下,如果我遇到任何问题,我会更新它
在Redux商店中,我有:
const initialState = {
Page: {
Theme: "light"
},
};
在主App.js文件中,我有
<MuiThemeProvider theme={theme(this.props.pageTheme)}>
如果您对此有任何改进建议,我们仍然非常感谢。您可以检查this.props是否未定义,然后尝试使用this.props.pageTheme获取主题。在redux初始存储中具有默认值。无论如何,当动作触发时,将有一个reducer来更新存储中的状态,组件将重新渲染。
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"
}
}
});
}