自学内容网 自学内容网

NextJs - SSR渲染解决antd首屏加载CSS样式的闪烁问题

NextJs - SSR渲染解决antd首屏加载CSS样式的闪烁问题

闪烁现状

我们写一个非常简单的页面:

import { Button } from 'antd'

export default async function Page() {

  return <>
    <Button type='primary'>AAA</Button>
  </>
}

NextJs中,通过SSR渲染,效果如下:
在这里插入图片描述

解决方案

1.安装:@ant-design/cssinjs

npm i @ant-design/cssinjs

2.新建一个:RootStyleRegistry

'use client'
import { useState, type PropsWithChildren } from 'react'
import { useServerInsertedHTML } from 'next/navigation'
import { createCache, extractStyle, StyleProvider } from '@ant-design/cssinjs'

export const RootStyleRegistry = ({ children }: PropsWithChildren) => {
  const [cache] = useState(() => createCache())

  useServerInsertedHTML(() => {
    return (
      <script
         dangerouslySetInnerHTML={{
          __html: `</script>${extractStyle(cache)}<script>`,
        }}
      />
    )
   })

   return <StyleProvider cache={cache}>{children}</StyleProvider>
}

3.我们在根Layout中,进行包裹:

import "./globals.css";
import { RootStyleRegistry } from './RootStyleRegistry'
export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) {
  return (
    <html lang="en">
      <body>
        <RootStyleRegistry>
          {children}
        </RootStyleRegistry>
      </body>
    </html>
  );
}

最终效果如下:样式闪烁问题解决
在这里插入图片描述


原文地址:https://blog.csdn.net/Zong_0915/article/details/140218296

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!