Rem*_*emi 16 reactjs material-ui
默认情况下,材料UI主题是几个预先定义的对象,例如的组合typography: {...},palette: {...}等等。
是否可以将自定义对象添加到此设置中并仍然使用createMuiTheme?
例如,主题对象将变为:
const theme = {
palette: {
primary: '#000'
},
typography: {
body1: {
fontFamily: 'Comic Sans'
}
},
custom: {
myOwnComponent: {
margin: '10px 10px'
}
}
}
Run Code Online (Sandbox Code Playgroud)
Rya*_*ell 22
是的,这很好用。Material-UI将其默认值与您提供的对象进行深度合并,并对以更复杂的方式(例如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);
Run Code Online (Sandbox Code Playgroud)
Nea*_*arl 17
您可以在 MUI 主题中添加自定义变量,如下所示:
const theme = createTheme({
myField: {
myNestedField: 'myValue',
},
});
Run Code Online (Sandbox Code Playgroud)
但如果您使用 Typescript,您还需要更新模块增强的定义ThemeOptions和Theme使用:
declare module '@mui/material/styles' {
// fix the type error when referencing the Theme object in your styled component
interface Theme {
myField?: {
myNestedField?: string;
};
}
// fix the type error when calling `createTheme()` with a custom theme option
interface ThemeOptions {
myField?: {
myNestedField?: string;
};
}
}
Run Code Online (Sandbox Code Playgroud)
Theme如果你想重用和之间的类型ThemeOptions,你可以定义一个公共接口并在两个地方继承它:
declare module '@mui/material/styles' {
interface CustomTheme {
myField?: {
myNestedField?: string;
};
}
interface Theme extends CustomTheme {}
interface ThemeOptions extends CustomTheme {}
}
Run Code Online (Sandbox Code Playgroud)
另请注意,如果您想使用 覆盖自定义组件,则不必在 MUI 主题中创建自定义变量createTheme()。有关更多详细信息,请参阅此答案。
| 归档时间: |
|
| 查看次数: |
11032 次 |
| 最近记录: |