gpt4 book ai didi

reactjs - 使用 Material-UI 主题更改根背景颜色

转载 作者:行者123 更新时间:2023-12-03 13:44:57 25 4
gpt4 key购买 nike

我正在尝试一些非常简单的事情:使用 Material-UI 主题为网站构建两个主题:

一个light主题和一个dark主题,但效果不佳:主题位于每个Material-UI React元素上,但位于html文档上的根元素上保持相同的默认白色背景。

当然可以通过用纯.css攻击body来改变:

body {
background-color: #222;
}

但是我想用 React 动态地改变它,我认为这会起作用,但事实并非如此:

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: {
default: "#222222",
}
},
});

ReactDOM.render(
<MuiThemeProvider theme = { themeDark }>
<App />
</MuiThemeProvider>, document.getElementById('root'));

我在这里迷路了,没有办法用 Material-UI 主题来做这个吗?

最佳答案

CssBaseline是控制这方面的组件。如果您没有使用 CssBaseline,那么您只会看到浏览器提供的默认值。

这是一个有效的 v4 示例(下面是 v5 示例):

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);

Edit theme body background

<小时/>

下面是一个 Material-UI v5 示例。与 v4 的唯一区别是 ThemeProvider 的名称更改(尽管除了 MuiThemeProvider 之外,v4 中也提供此名称)和 createTheme (改为createMuiTheme)并使用新的 @mui/material 包名称而不是 @material-ui/core

import React from "react";
import ReactDOM from "react-dom";
import CssBaseline from "@mui/material/CssBaseline";
import { ThemeProvider, createTheme } from "@mui/material/styles";
import Button from "@mui/material/Button";

const themeLight = createTheme({
palette: {
background: {
default: "#e4f0e2"
}
}
});

const themeDark = createTheme({
palette: {
background: {
default: "#222222"
},
text: {
primary: "#ffffff"
}
}
});

const App = () => {
const [light, setLight] = React.useState(true);
return (
<ThemeProvider theme={light ? themeLight : themeDark}>
<CssBaseline />
<Button onClick={() => setLight((prev) => !prev)}>Toggle Theme</Button>
</ThemeProvider>
);
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Edit theme body background

关于reactjs - 使用 Material-UI 主题更改根背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59145165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com