因此,我一直在与我的应用程序上的反应材料。到目前为止,一切都还可以,但是我想创建一个可以在后台存储主题的应用程序,并且可以根据用户选择加载主题。
所以直到现在,我知道我可以创建多个主题并将其存储为here 但是我想将它们存储到后端,但我不知道这将如何工作
所以我需要一个想法或某种教程的帮助,可以为我指明正确的方向吗?
答案 0 :(得分:2)
您只需要存储允许用户更改/指定的属性。例如,您可能只允许他们选择原色和副色。然后,您将把这两条信息保存在数据库中,然后使用createMuiTheme
重新创建主题。
以下是一些示例代码演示了这一点:
import React from "react";
import ReactDOM from "react-dom";
import CssBaseline from "@material-ui/core/CssBaseline";
import AppBar from "@material-ui/core/AppBar";
import Button from "@material-ui/core/Button";
import { createMuiTheme, MuiThemeProvider } from "@material-ui/core/styles";
const themeDB = {
a: {
primaryColor: "#0f0",
secondaryColor: "#f0f"
},
b: {
primaryColor: "#ff0",
secondaryColor: "#0ff"
}
};
const createThemeFromThemeDBEntry = themeDBEntry => {
return createMuiTheme({
palette: {
primary: {
main: themeDBEntry.primaryColor
},
secondary: {
main: themeDBEntry.secondaryColor
}
}
});
};
class App extends React.Component {
constructor(props) {
super(props);
this.state = { currentTheme: createMuiTheme() };
}
switchToThemeA = () => {
const themeA = createThemeFromThemeDBEntry(themeDB.a);
this.setState({ currentTheme: themeA });
};
switchToThemeB = () => {
const themeB = createThemeFromThemeDBEntry(themeDB.b);
this.setState({ currentTheme: themeB });
};
useDefaultTheme = () => {
this.setState({ currentTheme: createMuiTheme() });
};
render() {
return (
<>
<CssBaseline />
<MuiThemeProvider theme={this.state.currentTheme}>
<AppBar position="static">AppBar using Primary Color</AppBar>
<AppBar position="static" color="secondary">
AppBar using Secondary Color
</AppBar>
<br />
<Button
onClick={this.switchToThemeA}
variant="contained"
color="primary"
>
Use Theme A
</Button>
<Button
onClick={this.switchToThemeB}
variant="contained"
color="secondary"
>
Use Theme B
</Button>
<Button onClick={this.useDefaultTheme} color="secondary">
Use Default Theme
</Button>
</MuiThemeProvider>
</>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);