【问题标题】:How to use Google fonts in a React application using Next.js [closed]如何使用 Next.js 在 React 应用程序中使用 Google 字体 [关闭]
【发布时间】:2019-12-27 23:36:20
【问题描述】:

我正在使用 Next.js 构建一个基本的 React 应用程序,并且想知道如何在应用程序中使用 Google 字体。

是否可以在每个组件中导入字体或者我需要制作一个主样式表?

【问题讨论】:

  • 这可能很愚蠢,但是...我会像在纯 html 中一样在头部包含一个普通链接。只是你从谷歌获得的链接。并确保您的样式使用该字体。
  • 把这个放在你的 _document.js 头中:<script dangerouslySetInnerHTML={{__html: '</script><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" media="print" onload="this.media=\'all\'" /><script>' }} />source

标签: javascript css reactjs fonts next.js


【解决方案1】:

您可以通过为next.js 应用创建自定义document(需要在pages 文件夹中并命名为_document.js)轻松地将字体(全局)添加到您的应用中

import Document, { Html, Head, Main, NextScript } from 'next/document';

class CustomDocument extends Document {
  static async getInitialProps (ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    return { ...initialProps }
  }

  render() {
    return (
      <Html>
        <Head>
          <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" type="text/css" />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default CustomDocument;

您可以阅读更多关于它的信息here

【讨论】:

  • 虽然这行得通 - 资源在 Google 页面洞察中阻止了您页面的第一次绘制。
猜你喜欢
  • 1970-01-01
  • 2012-09-27
  • 1970-01-01
  • 2011-11-02
  • 2021-10-26
  • 2021-08-31
  • 2020-04-17
  • 1970-01-01
  • 2020-07-26
相关资源
最近更新 更多