使用Material UI的多字体Next.js

wkftcu5l  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(130)

我想在我的Next.js项目中使用Material UI的多种字体。我正在分享我的customeTheme.js:

import { ThemeProvider, createTheme } from "@mui/material/styles";
import { Roboto, Poppins, Bungee_Spice } from "next/font/google";

export const poppins = Poppins({
  subsets: ["latin"],
  display: "swap",
  weight: ["400", "600", "800"],
});

export const bungee_spice = Bungee_Spice({
  subsets: ["latin"],
  display: "swap",
  weight: ["400"],
});

const customTheme = createTheme({
  typography: {
    // fontFamily: bungee_spice.style.fontFamily, // This works
    fontFamily: {
      customFontOne: bungee_spice.style.fontFamily,
      customFontTwo: poppins.style.fontFamily,
    }, // This is not working
  },
});

export default customTheme;

字符串
我想使用这些自定义字体,如:

import { Box, Typography } from "@mui/material";

export default function Home() {
  return (
      <Box>
        <Typography sx={{ fontFamily: "customFontOne" }}>
          THIS IS A ROBOTO FONT this is a roboto font
        </Typography>
        <Typography sx={{ fontFamily: "customFontTwo" }}>
          THIS IS A POPPINS FONT this is a poppins font
        </Typography>
      </Box>
  );
}


如何在不同的行中使用不同的字体?

izj3ouym

izj3ouym1#

代码的问题在于您试图在主题中为fontFamily属性使用嵌套对象。材质UI不支持此操作。相反,您需要使用字符串数组。
下面是更新后的代码:

import { ThemeProvider, createTheme } from "@mui/material/styles";
    import { Roboto, Poppins, Bungee_Spice } from "next/font/google";
    
    export const poppins = Poppins({
      subsets: ["latin"],
      display: "swap",
      weight: ["400", "600", "800"],
    });
    
    export const bungee_spice = Bungee_Spice({
      subsets: ["latin"],
      display: "swap",
      weight: ["400"],
    });
    
    const customTheme = createTheme({
      typography: {
        fontFamily: ["bungee_spice", "poppins"],
      },
    });
    
    export default customTheme;

 Now, you can use the different fonts in different lines like this:

import { Box, Typography } from "@mui/material";

export default function Home() {
  return (
      <Box>
        <Typography sx={{ fontFamily: "bungee_spice" }}>
          THIS IS A ROBOTO FONT this is roboto font
        </Typography>
        <Typography sx={{ fontFamily: "poppins" }}>
          THIS IS A POPPINS FONT this is poppins font
        </Typography>
      </Box>
  );
}

字符串
这将使用Bungee Spice字体呈现第一行中的文本,使用Poppins字体呈现第二行中的文本。

相关问题