将自定义主题变量对象添加到createMuiTheme()

编程入门 行业动态 更新时间:2024-10-08 00:23:45
本文介绍了将自定义主题变量对象添加到createMuiTheme()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

默认情况下,实质性UI主题是几个预定义对象(例如typography: {...},palette: {...}等)的组合.

By default the material UI theme is a combination of several pre-defined objects such as typography: {...}, palette: {...} etc.

是否可以在此设置中添加自定义对象,并且仍然使用createMuiTheme?

Is is possible to add a custom object into this setup and still use createMuiTheme?

例如,主题对象将变为:

So for example the theme object would become:

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

推荐答案

是的,这很好. Material-UI执行将其默认值与您提供的对象进行深度合并,并对以更复杂的方式(例如palette,typography等)进行合并的键进行一些特殊处理.任何无法识别的密钥都将保持不变.

Yes, this works just fine. Material-UI does a deep merge of its defaults with the object you provide with some special handling for keys that get merged in a more sophisticated fashion (such as palette, typography and a few others). Any unrecognized keys will come through unchanged.

下面是一个有效的示例:

Below is a working example:

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

更多推荐

将自定义主题变量对象添加到createMuiTheme()

本文发布于:2023-11-11 08:39:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577911.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   变量   对象   主题   createMuiTheme

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!