gpt4 book ai didi

reactjs - 在 createTheme() 中添加自定义主题变量

转载 作者:行者123 更新时间:2023-12-03 13:41:53 27 4
gpt4 key购买 nike

默认情况下,MUI 主题是多个预定义对象的组合,例如 typography: {...}palette: {...} 等。

是否可以将自定义对象添加到此设置中并仍然使用createTheme

例如,主题对象将变为:

const theme = {
palette: {
primary: '#000'
},
typography: {
body1: {
fontFamily: 'Comic Sans'
}
},
custom: {
myOwnComponent: {
margin: '10px 10px'
}
}
}

最佳答案

是的,这很好用。 Material-UI 做了 deep merge of its defaults您提供的对象对以更复杂的方式合并的键进行了一些特殊处理(例如 palettetypography 和其他一些)。任何无法识别的键都将保持不变。

下面是一个工作示例:

import React from "react";
import ReactDOM from "react-dom";

import {
useTheme,
createMuiTheme,
MuiThemeProvider
} from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";
const theme = createMuiTheme({
palette: {
primary: {
main: "#00F"
}
},
typography: {
body1: {
fontFamily: "Comic Sans"
}
},
custom: {
myOwnComponent: {
margin: "10px 10px",
backgroundColor: "lightgreen"
}
}
});
const MyOwnComponent = () => {
const theme = useTheme();
return (
<div style={theme.custom.myOwnComponent}>
Here is my own component using a custom portion of the theme.
</div>
);
};
function App() {
return (
<MuiThemeProvider theme={theme}>
<div className="App">
<Button variant="contained" color="primary">
<Typography variant="body1">
Button using main theme color and font-family
</Typography>
</Button>
<MyOwnComponent />
</div>
</MuiThemeProvider>
);
}

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

Edit custom properties in theme

关于reactjs - 在 createTheme() 中添加自定义主题变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58168798/

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