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

2023-11-21

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

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

  1. When I enter the page: enter image description here

  2. After a few seconds: enter image description here

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


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

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

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

Modify next.config.js:

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

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

module.exports = nextConfig

创建自定义_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()
    }
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

样式需要时间加载 - Next.js 的相关文章

随机推荐