如何在NextJS 13的/app目录中使用Ant Design v5(非全CSR)
在NextJS 13 /app目录中使用Ant Design v5(非全页CSR方案)
核心思路是仅给用到AntD组件的局部代码标记'use-client',页面主体保持服务器渲染(SSR/SSG),既保留NextJS App Router的性能优势,又能正常使用AntD组件。
步骤1:安装依赖
执行安装命令:
npm install antd # 或 yarn add antd # 或 pnpm add antd
步骤2:全局样式与主题配置
AntD v5默认采用CSS-in-JS,若需要全局重置样式,在根布局app/layout.tsx中导入:
import 'antd/dist/reset.css';
如果要自定义主题,需用ConfigProvider(它依赖React Context,必须放在客户端组件中):
- 创建
components/Providers.tsx(客户端组件):
'use-client'; import { ConfigProvider } from 'antd'; import type { ReactNode } from 'react'; export default function Providers({ children }: { children: ReactNode }) { return ( <ConfigProvider theme={{ token: { colorPrimary: '#1890ff', // 自定义主题色 borderRadius: 6, }, }} > {children} </ConfigProvider> ); }
- 在根布局中引入这个Providers:
import './globals.css'; import 'antd/dist/reset.css'; import Providers from '@/components/Providers'; export default function RootLayout({ children }: { children: ReactNode }) { return ( <html lang="zh-CN"> <body> <Providers>{children}</Providers> </body> </html> ); }
步骤3:局部使用AntD组件(关键)
不要给整个页面加'use-client',而是把用到AntD组件的部分抽成单独的客户端组件,页面本身保持服务器渲染:
- 创建客户端组件
components/AntdDemo.tsx:
'use-client'; import { Card, Button, Table } from 'antd'; import type { ColumnsType } from 'antd/es/table'; interface DataType { key: string; name: string; age: number; address: string; } const columns: ColumnsType<DataType> = [ { title: '姓名', dataIndex: 'name', key: 'name' }, { title: '年龄', dataIndex: 'age', key: 'age' }, { title: '地址', dataIndex: 'address', key: 'address' }, ]; const data: DataType[] = [ { key: '1', name: '张三', age: 32, address: '北京' }, { key: '2', name: '李四', age: 42, address: '上海' }, ]; export default function AntdDemo() { return ( <div style={{ padding: '20px' }}> <Card title="服务器页面中的AntD组件"> <Button type="primary">交互按钮</Button> <Table columns={columns} dataSource={data} style={{ marginTop: '20px' }} /> </Card> </div> ); }
- 在服务器页面
app/page.tsx中引入该组件:
import AntdDemo from '@/components/AntdDemo'; // 这里可以执行服务器端逻辑,比如fetch数据 async function getServerData() { const res = await fetch('https://api.example.com/data', { cache: 'force-cache' }); return res.json(); } export default async function Home() { const serverData = await getServerData(); return ( <main> <h1>这是服务器渲染的内容:{serverData.title}</h1> {/* 引入客户端组件,仅这部分是CSR */} <AntdDemo /> </main> ); }
注意事项
- 所有依赖React状态、事件处理、DOM操作的AntD组件(如Modal、Tooltip、Dropdown等),必须放在标记了
'use-client'的组件中。 - 页面中的服务器端逻辑(如数据获取、静态生成)不受影响,依然保持SSR/SSG特性。
- 避免在服务器组件中直接导入AntD组件,会导致运行时错误。
内容的提问来源于stack exchange,提问作者Worthy Dev
相关产品推荐
相关产品推荐

