我在 Next.js React 项目中使用具有自定义主题的 Material-UI (MUI)。虽然主题的颜色已正确应用,但我无法更改 H2 和 H5 元素的默认字体大小。我已经在主题的排版对象中为这些标题级别定义了样式,但它们没有反映在渲染的 HTML 中。
这是next.js中的layout.js文件
"use client";
import { ThemeProvider, createTheme } from "@mui/material";
import "./globals.css";
const theme = createTheme({
palette: {
primary: {
dark: "#5d059c",
main: "#8608E0",
light: "#9e39e6",
contrastText: "#E9E1EF",
},
secondary: {
dark: "#3c1656",
main: "#56207C",
light: "#774c96",
contrastText: "#E9E1EF",
},
typography: {
h2: {
fontSize: "5rem",
fontWeight: 700,
},
h5: {
fontSize: "1rem",
fontWeight: 500,
},
},
},
});
export default function RootLayout({ children }) {
return (
<html lang="en">
<ThemeProvider theme={theme}>
<body>{children}</body>
</ThemeProvider>
</html>
);
}
这是我正在开发的组件
import { Box, Button, Container, Typography } from "@mui/material";
import React from "react";
const Nav = () => {
return (
<>
<Container
sx={{
bgcolor: "primary.light",
height: "13vh",
display: "flex",
justifyContent: "space-between",
width: "100%",
}}
>
<Box>
<Typography variant="h2">logo</Typography>
</Box>
<Box sx={{ display: "flex", gap: "2vh", alignItems: "center" }}>
<Typography variant="h5">about us</Typography>
<Typography variant="h5">contact</Typography>
<Typography variant="h5">more</Typography>
<Button color="secondary" variant="contained">
click here
</Button>
</Box>
</Container>
</>
);
};
export default Nav;
我已将此组件导出到应用程序中
但我仍然无法覆盖 h2 和 h5 的默认大小!!
与
palette
类似,您需要将typography
变量设置为createTheme
主题对象的第一级子对象,如下所示:
let theme = createTheme({
palette: {
primary: {
dark: '#5d059c',
main: '#8608E0',
light: '#9e39e6',
contrastText: '#E9E1EF',
},
secondary: {
dark: '#3c1656',
main: '#56207C',
light: '#774c96',
contrastText: '#E9E1EF',
},
},
typography: {
h2: {
fontSize: '5rem',
fontWeight: 700,
},
h5: {
fontSize: '1rem',
fontWeight: 500,
},
},
});
您可以查看 this StackBlitz,获取示例代码的实时工作示例。