首页 > 解决方案 > 自定义字体未加载到 Material UI 的自定义主题上

问题描述

我在我的 React Web 应用程序中使用自定义字体。所以我写了这段代码:

import React, { FunctionComponent } from 'react'
import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles'
import SofiaProLightTtf from '../../assets/font/sofia-pro-light.ttf'
import SofiaProTtf from '../../assets/font/sofia-pro-regular.ttf'

const sofiaPro = {
  fontFamily: 'Sofia Pro',
  fontStyle: 'normal',
  fontWeight: 100,
  src: `url(${SofiaProTtf})`
}

const sofiaProLight = {
  fontFamily: 'Sofia Pro Light',
  fontStyle: 'normal',
  fontWeight: 100,
  src: `url(${SofiaProLightTtf})`
}

const theme = createMuiTheme({
  typography: {
    fontFamily: 'Sofia Pro',
    body1: {
      fontFamily: 'Sofia Pro Light'
    }
  },
  overrides: {
    MuiCssBaseline: {
      '@global': {
        '@font-face': [sofiaPro, sofiaProLight]
      }
    }
  }
})

const Theme: FunctionComponent = ({ children }) => (
  <MuiThemeProvider theme={theme}>{ children }</MuiThemeProvider>
)

export default Theme

但它不起作用。所以我尝试使用纯 CSS 自定义字体。

我找到了一种解决方法,使用这个 CSS删除overrides属性:createMuiTheme

<style>
  @font-face {
    font-family: 'Sofia Pro';
    font-style: normal;
    font-weight: 100;
    src: url("/65e0f064b96a52b92f7293b673054b0b.ttf");
  }

  @font-face {
    font-family: 'Sofia Pro Light';
    font-style: normal;
    font-weight: 100;
    src: url("/d15399628129cc8121c08073df25f0dd.ttf");
  }
</style>

但这是一个非常糟糕的解决方法......是否有更好的解决方案,特定于使用 Material UI 的项目?我做错了createMuiTheme什么吗?

标签: javascriptcssreactjsmaterial-uifont-face

解决方案


您首先需要将您的 webpack 配置为使用字体或使用字体的链接或 cdn,在配置您的 webpack 以处理字体或使用 cdn 之后,您可以转到 theme.js 并添加您的字体,以便您可以全局使用它

import RalewayWoff2 from './fonts/Raleway-Regular.woff2';

const raleway = {
  fontFamily: 'Raleway',
  fontStyle: 'normal',
  fontDisplay: 'swap',
  fontWeight: 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',
};

在你的主题中像这样使用 cssbaseline

const theme = createMuiTheme({
  typography: {
    fontFamily: 'Raleway, Arial',
  },
  overrides: {
    MuiCssBaseline: {
      '@global': {
        '@font-face': [raleway],
      },
    },
  },
});

我从文档中得到这个

https://material-ui.com/customization/typography/


推荐阅读