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

时间:2019-09-30 13:20:58

标签: reactjs material-ui

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

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

例如,主题对象将变为:

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

1 个答案:

答案 0 :(得分:1)

是的,这很好。 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