默认情况下,材料UI主题是几个预先定义的对象,例如的组合typography: {...},palette: {...}等等。
typography: {...}
palette: {...}
是否可以在此设置中添加自定义对象并仍然使用createMuiTheme?
createMuiTheme
因此,例如主题对象将变为:
const theme = { palette: { primary: '#000' }, typography: { body1: { fontFamily: 'Comic Sans' } }, custom: { myOwnComponent: { margin: '10px 10px' } } }
是的,这很好。材料的UI做了它的默认深合并与您的一些特殊处理,它们会在一个更复杂的方式合并键提供的对象(如palette,typography和其他几个人)。任何无法识别的密钥都将保持不变。
palette
typography
下面是一个工作示例:
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);