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>
);
}
最终效果如下:样式闪烁问题解决