简体   繁体   English

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

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

I'm trying to import and use the Yellowtail font (from Google Fonts) in my React app in a Material-UI theme.我正在尝试在我的 React 应用程序中以 Material-UI 主题导入和使用 Yellowtail 字体(来自 Google Fonts)。

As far as i know all google fonts are on npm, I've installed it, with the据我所知,所有 google fonts 都在 npm 上,我已经安装了它,使用

npm install typeface-yellowtail --save npm 安装 typeface-yellowtail --save

command.命令。

I have imported it in App.js, put it in the font-family part of the theme, passed the theme to the MuiThemeProvider, but it does not work.我已经在 App.js 中导入它,将它放在主题的 font-family 部分,将主题传递给 MuiThemeProvider,但它不起作用。 What did I miss?我错过了什么?

This is what i have inside of App.js (header contains an AppBar with some grids and body contains only an h1 text for testing)这就是我在 App.js 中的内容(标头包含一个带有一些网格的 AppBar,正文仅包含一个用于测试的 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;

Instead of installing via npm, you can just first load CSS file.您可以先加载 CSS 文件,而不是通过 npm 安装。

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

Import this CSS file导入此 CSS 文件

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

Now you don't need to use any @font-face.现在你不需要使用任何@font-face。 This can be used with font families like normal.这可以与正常的字体系列一起使用。

You are missing three things:你错过了三件事:

  • Import the npm package as something导入 npm package作为东西
  • Use the CssBaseline component使用CssBaseline组件
  • Add an override to the object provided to createMuiTheme()添加对提供给createMuiTheme()的 object 的override

See example:参见示例:

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;

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

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

Notes笔记

  • MuiThemeProvider changed to ThemeProvider in the transition from Material-UI v3 to v4. MuiThemeProvider在从 Material-UI v3 到 v4 的过渡中更改为ThemeProvider If you are on v4, this is the only change needed - this example code otherwise works on both versions.如果您使用的是 v4,这是唯一需要的更改 - 此示例代码在两个版本上都适用。

  • You must wrap text in Material-UI's Typography component for the font to be used.您必须在 Material-UI 的Typography组件中换行文本才能使用字体。

There is a much easier way of doing this that doesn't require a .css file or installing any extra packages.有一种更简单的方法可以做到这一点,不需要.css文件或安装任何额外的包。

If your font is available over a CDN like Google Fonts then just imported into the root HTML file of your app:如果您的字体可以通过像Google Fonts这样的 CDN 获得,那么只需导入到您应用程序的根 HTML 文件中:

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

Then add one line in the Material-UI theme:然后在Material-UI主题中添加一行:

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

Working codesandbox example with Material-UI v5. 使用 Material-UI v5 的工作代码和框示例。

Update : Since @ekkis mentioned I'm adding further details on how to include the Google Font.更新:由于@ekkis提到我正在添加有关如何包含 Google 字体的更多详细信息。 The following answer assumes you're using Material UI v4.10.1以下答案假设您使用的是 Material UI v4.10.1

  1. Install the gatsby-plugin-web-font-loader to install Google font.安装gatsby-plugin-web-font-loader以安装 Google 字体。

  2. Edit gatsby-config.js to include the plugin and the Google font.编辑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. To use the font, create a file called theme.js in src/components要使用字体,请在src/components中创建一个名为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. Now that you've the theme export, you can use it in your components.现在您已经导出了theme ,您可以在组件中使用它。

  2. Import theme on to your components.theme导入您的组件。 Let's say <Layout /> is your main component.假设<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. To use Google font in other components, just use要在其他组件中使用 Google 字体,只需使用
<Typography ...>Some Text</Typography> 

As long as these components use as their parent, these components will continue to use the Google Font.只要这些组件用作其父组件,这些组件就会继续使用 Google 字体。 Hope this helps.希望这可以帮助。


Old Answer:老答案:

Place your text in the Typography component to reflect the Google Font you installed via npm将您的文本放在Typography组件中以反映您通过npm安装的 Google 字体

import { Typography } from "@material-ui/core"

Assume you have some text in <AppBody>假设您在<AppBody>中有一些文本

<AppBody>
    Hello World!
</AppBody>

The above text should now be changed to上面的文字现在应该改为

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

Refer Material UI docs for the different variants.请参阅Material UI 文档了解不同的变体。

I have define my font in main CSS file( index.css )我在主 CSS 文件中定义了我的字体( index.css

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

and then in the App.tsx I added theme然后在App.tsx中我添加了theme

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

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

Note that it is for Typography components.请注意,它适用于Typography组件。

This worked for me:这对我有用:

  1. Install your font as a package using @fontsource on npm, ie:在 npm 上使用@fontsource 将字体安装为 package,即:
npm i @fontsource/work-sans
  1. Add to your _app.js your import, this makes your package (font) accessible globally添加到您的_app.js您的导入,这使您的 package(字体)可在全球范围内访问
const workSans = require('@fontsource/work-sans');
  1. In your theme modify your typography:在你的主题中修改你的排版:
...
  typography: {
      fontFamily: 'Work Sans',
    }
...

That's it!就是这样!

I want to add to @georgeos answer that a small revision of the proposed solution worked for me:我想在@georgeos 的回答中补充一点,对我提出的解决方案进行了小幅修改:

export const theme = createTheme({
    ...
    components: {
        MuiCssBaseline: {
            styleOverrides: {
                '@global': {
                    '@font-face': [Inter, Nunito],
                 },
            },
        },
    },
    ...
});

I also needed to add the following to the app.ts file ( source ):我还需要将以下内容添加到app.ts文件 ( source ):

function App(){
    ...
    return (
        <ThemeProvider theme={theme}>
            <CssBaseline enableColorScheme /> <---
        ...
        </ThemeProvider>);
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM