本文介绍了将自定义主题变量对象添加到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执行将其默认值与您提供的对象进行深度合并,并对以更复杂的方式(例如palettetypography等)进行合并的键进行一些特殊处理.任何无法识别的密钥都将保持不变.

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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:09