如何在 material-ui 主题中导入和使用自定义字体?

How to import and use a custom font in a material-ui theme?

我正在尝试在我的 Material-UI 主题的 React 应用中导入和使用 Yellowtail 字体(来自 Google 字体)。

据我所知,所有 google 字体都在 npm 上,我已经安装了它,

npm install typeface-yellowtail --save

命令。

我在App.js里导入了,放在主题的font-family部分,把主题传给了MuiThemeProvider,还是不行。我错过了什么?

这就是我在 App.js 中的内容(header 包含带有一些网格的 AppBar,而 body 仅包含用于测试的 h1 文本)

import React, { Component, Fragment } from 'react';
import Header from './Components/Layouts/Header';
import AppBody from './Components/Layouts/AppBody';
import Footer from './Components/Layouts/Footer'; 
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core';
import 'typeface-yellowtail';

const theme = createMuiTheme({  
  typography: {
    fontFamily: 
      '"Yellowtail", cursive',
  },
});

class App extends Component {
  render() {
    return (
      <MuiThemeProvider theme={theme}>
        <Header />
        <AppBody />
        <Footer />       
      </MuiThemeProvider>
    );
  }
}

export default App;

您可以先加载 CSS 文件,而不是通过 npm 安装。

@import url('https://fonts.googleapis.com/css?family=Yellowtail&display=swap');

导入此 CSS 文件

import './assets/css/yellowtail.css';

现在您不需要使用任何@font-face。这可以与正常的字体系列一起使用。

更新:由于提到了 @ekkis,我将添加有关如何包含 Google 字体的更多详细信息。以下答案假设您使用的是 Material UI v4.10.1

  1. 安装gatsby-plugin-web-font-loader安装Google字体。

  2. 编辑 gatsby-config.js 以包含插件和 Google 字体。

module.exports = {
  plugins:      [
    {
      resolve: "gatsby-plugin-web-font-loader",
      options: {
        google: {
          families: ["Domine", "Work Sans", "Happy Monkey", "Merriweather", "Open Sans", "Lato", "Montserrat"]
        }
      }
    },
  ]
}
  1. 要使用该字体,请在 src/components
  2. 中创建一个名为 theme.js 的文件
import {
  createMuiTheme,
  responsiveFontSizes
} from "@material-ui/core/styles"

let theme = createMuiTheme({
  typography: {
    fontFamily: [
                  "Work Sans",
                  "serif"
                ].join(","),
    fontSize:   18,
  }
})

// To use responsive font sizes, include the following line
theme     = responsiveFontSizes(theme)

export default theme
  1. 现在您已经有了 theme 导出,您可以在您的组件中使用它。

  2. theme 导入您的组件。假设 <Layout /> 是您的主要组成部分。

// src/components/layout.js

/**
 * External
 */
import React from "react"
import PropTypes from "prop-types"
import {
  ThemeProvider
} from "@material-ui/styles"
import { Typography } from "@material-ui/core"

/**
 * Internal
 */
import theme from "./theme"

const Layout = ({ children }) => {

  return (
    <>
      <ThemeProvider theme={theme}>
        <Typography variant="body1">Hello World!</Typography>
      </ThemeProvider>
    </>
  )
}
  1. 要在其他组件中使用Google字体,只需使用
<Typography ...>Some Text</Typography> 

只要这些组件用作它们的父组件,这些组件就会继续使用 Google 字体。希望这有帮助。


旧答案:

将您的文本放在 Typography 组件中以反映您通过 npm

安装的 Google 字体
import { Typography } from "@material-ui/core"

假设您在 <AppBody>

中有一些文本
<AppBody>
    Hello World!
</AppBody>

上面的文字现在应该改为

<AppBody>
    <Typography variant="body1">Hello World!</Typography>
</AppBody>

参考 Material UI docs 了解不同的变体。

您缺少三件事:

  • 导入 npm 包 as something
  • 使用CssBaseline组件
  • 向提供给 createMuiTheme() 的对象添加 override

参见示例:

import React, { Component, Fragment } from 'react';
import Header from './Components/Layouts/Header';
import AppBody from './Components/Layouts/AppBody';
import Footer from './Components/Layouts/Footer'; 
import { MuiThemeProvider, createMuiTheme, CssBaseline } from '@material-ui/core';
import yellowtail from 'typeface-yellowtail';

const theme = createMuiTheme({  
  typography: {
    fontFamily: 
      '"Yellowtail", cursive',
  },
  overrides: {
    MuiCssBaseline: {
      '@global': {
        '@font-face': [yellowtail],
      },
    },
  },
});

class App extends Component {
  render() {
    return (
      <MuiThemeProvider theme={theme}>
        <CssBaseline />
        <Header />
        <AppBody />
        <Footer />       
      </MuiThemeProvider>
    );
  }
}

export default App;

示例 CodeSandbox (MUI v3): https://codesandbox.io/s/late-pond-gqql4?file=/index.js

示例 CodeSandbox (MUI v4): https://codesandbox.io/s/pensive-monad-eqwlx?file=/index.js

注释

  • MuiThemeProvider 在从 Material-UI v3 到 v4 的过渡中更改为 ThemeProvider。如果您使用的是 v4,这是唯一需要的更改 - 此示例代码在其他情况下适用于两个版本。

  • 您必须将文本换行在 Material-UI 的 Typography 组件中才能使用字体。

有一种更简单的方法可以做到这一点,不需要 .css 文件或安装任何额外的包。

如果您的字体可以通过 Google Fonts 这样的 CDN 获得,那么只需导入到您应用的根 HTML 文件中:

<link
  href="https://fonts.googleapis.com/css2?family=Yellowtail&display=swap"
  rel="stylesheet"
/>

然后在Material-UI主题中添加一行:

const theme = createTheme({
  typography: { fontFamily: ["Yellowtail", "cursive"].join(",") }
});

Working codesandbox example with Material-UI v5.

我在主 CSS 文件中定义了我的字体(index.css)

@font-face {
    font-family: 'mikhak';
    src: url(./fonts/mikhak.ttf) format("truetype")
}

然后在 App.tsx 我添加了 theme

const theme = createTheme({
    typography: {
        fontFamily: 'mikhak, Raleway, Arial',
    }
});
    

ReactDOM.render(
    <ThemeProvider theme={theme}>
        <App />
    </ThemeProvider>,
    document.getElementById('root')
);

请注意,它适用于 Typography 个组件。