Logo
Next.js 使用 Antd 组件库样式偏移解决方案
所属分类:开发笔记
阅读量:745
评论数量:2
发布时间:2024-12-12 08:51
AI总结
ThriveX GPT
|

Next.js 使用 Antd 组件库样式偏移解决方案

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>
}

作者:宇阳

版权:此文章版权归 宇阳 所有,如有转载,请注明出处!

空状态
评论列表为空~
目录
作者头像

一直对网站开发领域很感兴趣,从小就希望有一个属于自己的网站,在17年时候成功进入站长圈,并通过各种自学,以及各种折腾,才有了你现在看到的这个网站

ICP豫ICP备2020031040号-1
月亮搜索订阅返回顶部
Next.js 使用 Antd 组件库样式偏移解决方案