使用Material-UI主题更改根背景颜色 [英] Change root background color with Material-UI theme
问题描述
我正在尝试一些非常简单的方法:使用Material-UI主题为网站构建两个主题:
I'm trying something very simple: building two themes for a website using Material-UI themes:
一个light
主题和一个dark
主题,但效果不佳:主题位于每个Material-UI react元素上,但是html文档上的根元素仍然具有相同的默认白色背景.
A light
theme and dark
one, but it does not work well: the theme is on every Material-UI react element, but the root element on the html document keeps having the same default white background.
当然可以通过使用纯.css攻击身体来更改它:
Of course it can be changed by attacking the body with pure .css:
body {
background-color: #222;
}
但是我一直想通过React动态地对其进行更改,尽管我可以这样做,但不能:
But I was looking to change it dynamically with React, I though this would work, but it does not:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { ThemeProvider } from '@material-ui/styles';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
const themeLight = createMuiTheme({
palette: {
background: {
default: "#e4f0e2"
}
},
});
const themeDark = createMuiTheme({
palette: {
background: {
paper: "#222222",
}
},
});
ReactDOM.render(
<MuiThemeProvider theme = { themeDark }>
<App />
</MuiThemeProvider>, document.getElementById('root'));
我在这里迷路了,没有办法用Material-UI主题来做到这一点吗?
and I'm lost here, there is no way to make this with Material-UI theme?
推荐答案
CssBaseline is the component that controls this aspect. If you aren't using CssBaseline
, then you are just seeing the default provided by the browser.
这是一个有效的示例:
import React from "react";
import ReactDOM from "react-dom";
import CssBaseline from "@material-ui/core/CssBaseline";
import { MuiThemeProvider, createMuiTheme } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
const themeLight = createMuiTheme({
palette: {
background: {
default: "#e4f0e2"
}
}
});
const themeDark = createMuiTheme({
palette: {
background: {
default: "#222222"
},
text: {
primary: "#ffffff"
}
}
});
const App = () => {
const [light, setLight] = React.useState(true);
return (
<MuiThemeProvider theme={light ? themeLight : themeDark}>
<CssBaseline />
<Button onClick={() => setLight(prev => !prev)}>Toggle Theme</Button>
</MuiThemeProvider>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
这篇关于使用Material-UI主题更改根背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!