导入新的字体系列并覆盖 @mui/material 字体系列组件。

3
我想要在字体文件夹中导入新的字体系列,并覆盖Mui基础字体系列。
import { responsiveFontSizes, createTheme } from '@mui/material';

import NEWFONTFAMILLY from '../fonts/something.otf'

const theme = responsiveFontSizes(
    createTheme({
        components: {
            MuiCssBaseline: {
                styleOverrides: {
                    fontFamily: [NEWFONTFAMILLY],
                },
            },
        },
    })
);

export default theme;

如果我使用这些代码,mui字体系列会被应用而不是我的字体系列:
@font-face {
    font-family: 'NEWFONTFAMILLY';
    src: url(../fonts/something.otf) format('opentype');
}

* {
    font-family: 'NEWFONTFAMILLY';
}

请问有人可以帮我吗?

我正在使用 @mui/material 版本5或更高的版本。


这个有帮助吗?https://mui.com/customization/typography/ - Julia
2个回答

0

我已经通过 MUI 文档 中提供的示例实现了这一点:

我建议使用 WOFF2 或 WOFF 文件,不确定是否与 OTF 兼容。

// first import your font file
import RalewayWoff2 from './fonts/Raleway-Regular.woff2';

const theme = createTheme({
  // override the theme fontFamily
  typography: {
    fontFamily: 'Raleway, Arial',
  },
  components: {
    MuiCssBaseline: {
     // add font-face to MuiCssBaseline component
      styleOverrides: `
        @font-face {
          font-family: 'Raleway';
          font-style: normal;
          font-display: swap;
          font-weight: 400;
          src: local('Raleway'), local('Raleway-Regular'), url(${RalewayWoff2}) format('woff2');
          unicodeRange: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF;
        }
      `,
    },
  },
});

然后,当您想要添加包含在您正在使用的主题中的组件时,可以像这样进行包装:

return (
  <ThemeProvider theme={theme}>
    <CssBaseline />
    <Box
      sx={{
        fontFamily: 'Raleway',
      }}
    >
      Raleway
    </Box>
  </ThemeProvider>
);

0

尝试使用稍微不同的语法:

  createTheme({
    components: {
      MuiCssBaseline: {
        styleOverrides: {
          '@font-face': NEWFONTFAMILLY,
        },
      },
    },
  })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接