在 NextJS
项目中使用 Ant Design
组件库时,我们会遇到布局偏移的问题,尤其是在首次加载时。
这个问题不仅 NextJS
存在,NuxtJS
也同样存在。
解决这个问题的方式也很简单,本文带领大家解决这个问题
首先
第一步: 在项目中创建一个 RootStyleRegistry
组件,用于管理样式缓存
'use client'
import { useState, type PropsWithChildren } from 'react'
import { useServerInsertedHTML } from 'next/navigation'
import { createCache, extractStyle, StyleProvider } from '@ant-design/cssinjs'
export default ({ children }: PropsWithChildren) => {
const [cache] = useState(() => createCache())
useServerInsertedHTML(() => {
return (
<script
dangerouslySetInnerHTML={{
__html: `</script>${extractStyle(cache)}<script>`,
}}
/>
)
})
return (
<>
<StyleProvider cache={cache}>
{children}
</StyleProvider>
</>
)
}
第二步: 在 src/app/layout.tsx
中使用 RootStyleRegistry
包裹子组件
export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
return (
<html lang="en">
<body>
{/* 核心代码 */}
<RootStyleAntd>{children}</RootStyleAntd>
</body>
</html>
);
}
第三步: 在页面中使用
'use client'
import { Button } from 'antd'
export default () => {
return <Button type="primary">大功告成!</Button>
}