样式需要时间加载 - Next.js

Jos*_*nça 5 styled-components next.js

当我输入我的作品集时,它会加载未样式化的 html 页面,并且仅在几秒钟后才会加载样式。我该如何解决这个问题?

注意:我正在使用样式组件

  1. 当我进入页面时: 在此输入图像描述

  2. 几秒钟后: 在此输入图像描述

我尝试寻找样式组件与 next.js 的兼容性,但找不到有关此错误的任何内容

iva*_*ias 12

作为 CSS-in-JS 样式解决方案,styled-components 适合客户端渲染,它通常假设它在浏览器中执行,因此它会根据 JavaScript 执行生成 CSS 样式,并将它们直接注入到文档中。在这种情况下,由于 Next.js 默认预渲染所有页面,因此您需要在服务器端渲染的 HTML 中使用 CSS 样式,以避免首次渲染时出现无样式内容的闪烁。

您可以按照以下步骤操作:

如果您使用 Next.js 12+(带有 SWC 编译器):

调整next.config.js

/** @type {import('next').NextConfig} */

const nextConfig = {
  // ...rest of options
  compiler: {
    styledComponents: true,
  },
}

module.exports = nextConfig
Run Code Online (Sandbox Code Playgroud)

_document.js在文件夹上创建自定义文件pages并添加:

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

export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    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()
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


Bar*_*zko 7

如果您将 Next 13 或 Next 14 与 App Router 一起使用,则 _document.js 解决方案将不起作用。然后,您需要创建一个全局注册表组件来收集渲染期间的所有 CSS 样式规则。

在 /app 文件夹中添加registry.tsx

'use client';

import React, { useState } from 'react';
import { useServerInsertedHTML } from 'next/navigation';
import {
  ServerStyleSheet,
  StyleSheetManager,
} from 'styled-components';

export default function StyledComponentsRegistry({
  children,
}: {
  children: React.ReactNode;
}) {
  // Only create stylesheet once with lazy initial state
  // x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
  const [styledComponentsStyleSheet] = useState(
    () => new ServerStyleSheet()
  );

  useServerInsertedHTML(() => {
    const styles = styledComponentsStyleSheet.getStyleElement();
    styledComponentsStyleSheet.instance.clearTag();
    return <>{styles}</>;
  });

  if (typeof window !== 'undefined') return <>{children}</>;

  return (
    <StyleSheetManager sheet={styledComponentsStyleSheet.instance}>
      {children}
    </StyleSheetManager>
  );
}
Run Code Online (Sandbox Code Playgroud)

然后导入它并在您的 app/layout.tsx 中使用。

import StyledComponentsRegistry from './lib/registry'
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html>
      <body>
        <StyledComponentsRegistry>{children}</StyledComponentsRegistry>
      </body>
    </html>
  )
}
Run Code Online (Sandbox Code Playgroud)

示例:https://github.com/vercel/app-playground/tree/main/app/styling/styled-components