一、初始化项目
npx create-next-app@latest admin-system
cd admin-system
二、安装依赖
npm install antd @ant-design/icons @ant-design/pro-components --save
# 或
yarn add antd @ant-design/icons @ant-design/pro-components
三、配置 Ant Design
1. 修改 _app.tsx
引入样式
// pages/_app.tsx
import 'antd/dist/reset.css';
import type { AppProps } from 'next/app';
import Layout from '@/components/Layout';
export default function App({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />;
}
2. 配置主题(可选)
创建 next.config.js
:
// next.config.js
const withAntdLess = require('next-plugin-antd-less');
module.exports = withAntdLess({
lessVarsFilePath: './src/styles/variables.less', // 自定义主题文件路径
webpack(config) {
return config;
},
});
四、创建基础布局
1. 创建布局组件 src/components/Layout/index.tsx
import { Layout, Menu } from 'antd';
import {
DashboardOutlined,
UserOutlined,
FileOutlined,
} from '@ant-design/icons';
import { useRouter } from 'next/router';
const { Header, Sider, Content } = Layout;
export default function AdminLayout({ children }) {
const router = useRouter();
const [collapsed, setCollapsed] = useState(false);
const menuItems = [
{ key: '/dashboard', icon: <DashboardOutlined />, label: '仪表盘' },
{ key: '/users', icon: <UserOutlined />, label: '用户管理' },
{ key: '/posts', icon: <FileOutlined />, label: '内容管理' },
];
return (
<Layout style={{ minHeight: '100vh' }}>
<Sider collapsible collapsed={collapsed} onCollapse={setCollapsed}>
<div className="logo" />
<Menu
theme="dark"
selectedKeys={[router.pathname]}
items={menuItems}
onClick={({ key }) => router.push(key)}
/>
</Sider>
<Layout>
<Header style={{ padding: 0, background: '#fff' }} />
<Content style={{ margin: '16px' }}>
<div style={{ padding: 24, background: '#fff', minHeight: 360 }}>
{children}
</div>
</Content>
</Layout>
</Layout>
);
}
2. 使用布局
修改 _app.tsx
// pages/_app.tsx
import 'antd/dist/reset.css';
import type { AppProps } from 'next/app';
import Layout from '@/components/Layout';
export default function App({ Component, pageProps }: AppProps) {
return (
<Layout>
<Component {...pageProps} />
</Layout>
);
};
// pages/dashboard.tsx
export default function Dashboard() {
return (
<h1>仪表盘</h1>
);
}
五、路由与页面管理
Next.js 使用文件系统路由:
pages/
├─ dashboard.tsx
├─ users/
│ ├─ index.tsx # /users
│ └─ [id].tsx # /users/123
└─ posts/
├─ index.tsx
└─ [id].tsx
登录页:
"use client";
// app/page.tsx
import React from "react";
import { Form, Input, Button, Typography } from "antd";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { useRouter } from "next/navigation";
const { Title } = Typography;
const RegisterPage: React.FC = () => {
const [form] = Form.useForm();
const router = useRouter();
const onFinish = (values: any) => {
console.log("Received values of form: ", values);
// 这里可以添加注册逻辑
router.replace("/dashboard");
};
return (
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "100vh",
}}
>
<Form
form={form}
name="login"
initialValues={{ remember: true }}
onFinish={onFinish}
style={{ width: "300px" }}
>
<Title level={3} style={{ textAlign: "center" }}>
登录
</Title>
<Form.Item
name="username"
rules={[{ required: true, message: "请输入用户名!" }]}
>
<Input
prefix={<UserOutlined className="site-form-item-icon" />}
placeholder="用户名"
/>
</Form.Item>
<Form.Item
name="password"
rules={[{ required: true, message: "请输入密码!" }]}
>
<Input.Password
prefix={<LockOutlined className="site-form-item-icon" />}
placeholder="密码"
/>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" style={{ width: "100%" }}>
登录
</Button>
</Form.Item>
</Form>
</div>
);
};
export default RegisterPage;
六、集成常用功能
1. 表格示例
import { Table, Button } from 'antd';
import { useQuery } from '@tanstack/react-query';
const UsersPage = () => {
const { data, isLoading } = useQuery(['users'], fetchUsers);
const columns = [
{ title: '姓名', dataIndex: 'name' },
{ title: '邮箱', dataIndex: 'email' },
{ title: '操作', render: (_, record) => (
<Button onClick={() => handleEdit(record.id)}>编辑</Button>
)},
];
return <Table dataSource={data} columns={columns} loading={isLoading} />;
};
2. 表单验证
import { Form, Input, Button } from 'antd';
const UserForm = ({ onSubmit }) => {
return (
<Form onFinish={onSubmit}>
<Form.Item
label="用户名"
name="username"
rules={[{ required: true, message: '请输入用户名' }]}
>
<Input />
</Form.Item>
{/* 更多表单项 */}
<Button type="primary" htmlType="submit">提交</Button>
</Form>
);
};
七、权限控制
1. 高阶组件保护路由
// components/AuthWrapper.tsx
import { useEffect } from 'react';
import { useRouter } from 'next/router';
export default function AuthWrapper(WrappedComponent) {
return (props) => {
const router = useRouter();
const isAuthenticated = /* 从全局状态或cookie获取 */;
useEffect(() => {
if (!isAuthenticated) router.push('/login');
}, [isAuthenticated]);
return isAuthenticated ? <WrappedComponent {...props} /> : null;
};
}
2. 使用示例
// pages/dashboard.tsx
export default AuthWrapper(Dashboard);
八、部署优化
- 静态导出:
next export
生成静态文件 - 按需加载:使用动态导入优化体积
import dynamic from 'next/dynamic';
const Chart = dynamic(() => import('@/components/Chart'), { ssr: false });
最终项目结构
git地址:https://github.com/Yuelf12345/next
admin-system/
├─ src/
│ ├─ app/
│ ├─ global.module.css
│ ├─ globals.css
│ ├─ layout.tsx
│ ├─ page.tsx
│ ├─ components/
│ └─ Layout/
│ └─ index.tsx
│ ├─ styles/
│ ├─ utils/
│ ├─types/
│ └─ pages/
│ ├─ _app.tsx
│ ├─ dashboard.tsx
│ ├─ users/
│ └─ posts/
├─ next.config.js
└─ package.json
通过以上步骤,你可以快速搭建一个基于 Next.js + Ant Design 的后台管理系统。实际开发中还需根据需求添加状态管理(如 Redux/Zustand)、API 集成、错误处理等模块。