【问题标题】:Can't import Google Fonts with Styled Components and Next.js无法使用样式化组件和 Next.js 导入 Google 字体
【发布时间】:2020-12-03 21:13:15
【问题描述】:

我在尝试加载 Google 字体时遇到了以下问题。我读到我应该在_document.js 中写这样的东西来将它导入到头部标签中

import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
  render() {
    return (
      <Html lang="en">
        <Head>
          <link
            rel="preload"
            href="/fonts/noto-sans-v9-latin-regular.woff2"
            as="font"
            crossOrigin=""
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}
export default MyDocument;

但这是我必须用来使 Styled Components 与 Next.js 一起使用的代码

import Document, { DocumentContext } from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
        });

      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      };
    } finally {
      sheet.seal();
    }
  }
}

所以我的问题是:如何修改我的 _document.js 文件以使用 Google 字体的样式?

另外,如果有任何帮助,这是我正在使用的 GlobalStyle,它不会导入字体

import { createGlobalStyle } from '@xstyled/styled-components';

const GlobalStyle = createGlobalStyle`

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

* {
    margin: 0;
    padding: 0;
}

*,
*::before,
*::after {
    box-sizing: inherit;
}

html {
    box-sizing: border-box;
    font-size: 62.5%; 
    position: relative;
    background: grey;
}

body {
  font-family: 'Lato', sans-serif;
}
`;

const BasicLayout = ({ children }: { children: any }) => {
  return (
    <>
      <GlobalStyle />
      {children}
    </>
  );
};

export default BasicLayout;

【问题讨论】:

标签: css reactjs next.js server-side-rendering styled-components


【解决方案1】:

前往此页面。

https://nextjs.org/docs/advanced-features/custom-app

请阅读自定义_app.js,然后执行以下操作:

首先,您需要为您的应用创建一个自定义_app.js。 (这必须在您的页面目录的根目录中)

那你需要在同一目录下创建_app.css

然后将css文件导入你的_app.js

import "./_app.css";

然后在您的 _app.css 文件中,导入您的 google 字体,如下所示:

@import url("https://fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&display=swap");

在 css 文件和 body 标签中添加以下行:

body {
  font-family: "PT Sans Narrow", sans-serif;
  etc..
}

【讨论】:

  • 我忘记了_app.js 是一个东西,所以我尝试从import Head from 'next/head' 添加一个Head 标签,它成功了
猜你喜欢
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 2013-06-14
  • 2023-04-05
  • 2021-09-29
  • 2022-01-22
  • 2018-03-14
相关资源
最近更新 更多