警告:道具“className”不匹配。在 NextJS 中使用 @font-face 和 styled-components 时

Warning: Prop `className` did not match. when using @font-face and styled-components with NextJS

大家好,我创建了一个 GlobalStyle,我使用 font-face.

调用我的字体
import { createGlobalStyle } from 'styled-components';

export const GlobalStyle = createGlobalStyle`
body {
    font-family: 'Roboto', sans-serif;
}
  html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font-family: 'Roboto', sans-serif;
    vertical-align: baseline;
}
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}
@font-face {
  font-family: "Roboto";
  src: url("/fonts/Roboto/Roboto-Regular.ttf");
  font-style: normal;
  font-weight: 400;
  font-display: swap;
}
@font-face {
  font-family: "Roboto";
  src: url("/fonts/Roboto/Roboto-Bold.ttf");
  font-style: bold;
  font-weight: 700;
  font-display: swap;
}
`;

这个 GlobalStyle 在我的 _app.tsx 文件中调用。字体位于我的 public 文件夹中。

我从来没有遇到过这个错误,但是在我添加 @font-face 之后这个问题开始了。

我尝试过的:

将此代码添加到 .babelrc:

"plugins": [["styled-components", { "ssr": true }]]

安装了 babel-preset-nextbabel-plugin-styled-components 扩展程序。

没有任何效果。 我做错了什么?

styled-components版本:5.3.0 下一个:11.0.1

修复了在页面文件夹中创建 _document.tsx 文件的问题。

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

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

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

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