🎨 Ant Design 与 AI 组件库使用指南

掌握 Ant Design 6 组件、Ant Design X(AI 组件库)、CSS Modules 配合和主题定制

Kuai 前端使用 Ant Design 6 作为基础 UI 库,Ant Design X 作为 AI 对话专用组件库,配合 CSS Modules 进行样式隔离。本课程详细介绍这些 UI 工具在项目中的使用方式。

📚 前置知识

🐜 Ant Design 6 概述

Ant Design(简称 antd)是蚂蚁金服开源的企业级 UI 设计语言和 React 组件库。Kuai 前端使用的是 Ant Design 6 版本,提供了丰富的开箱即用组件。

项目中的核心组件

分类组件用途
布局Layout页面整体布局(Header + Sider + Content)
Layout.Sider侧边栏导航
Layout.Header顶部导航栏
Layout.Content主内容区域
导航Menu侧边栏菜单(配合 navbarMenu 配置)
Breadcrumb面包屑导航
Tabs标签页切换
数据展示Table数据表格(列表页核心组件)
Card卡片容器
Tag标签(状态标记)
Descriptions描述列表(详情页)
数据录入Form表单(创建/编辑页面)
Input输入框
Select下拉选择器
Modal弹窗(确认操作、表单弹窗)
反馈message全局提示(操作成功/失败)
notification通知提醒(更详细的通知)
Spin加载中状态

按需导入

// Ant Design 6 支持 Tree Shaking,按需导入即可
import { Button, Table, Form, Input, Modal, message } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';

📝 常用组件使用示例

Table 数据表格

import { Table, Tag, Button, Space } from 'antd';

function ServerList({ servers, loading }) {
  const columns = [
    {
      title: '服务器名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={status === 'running' ? 'green' : 'red'}>
          {status}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button size="small" onClick={() => handleStart(record)}>启动</Button>
          <Button size="small" danger onClick={() => handleStop(record)}>停止</Button>
        </Space>
      ),
    },
  ];

  return (
    <Table
      columns={columns}
      dataSource={servers}
      loading={loading}
      rowKey="name"
    />
  );
}

Form 表单

import { Form, Input, Select, Button, message } from 'antd';

function AddServerForm({ onSubmit }) {
  const [form] = Form.useForm();

  const handleSubmit = async (values) => {
    try {
      await onSubmit(values);
      message.success('服务器添加成功');
      form.resetFields();
    } catch (err) {
      message.error('添加失败: ' + err.message);
    }
  };

  return (
    <Form form={form} onFinish={handleSubmit} layout="vertical">
      <Form.Item
        label="服务器名称"
        name="name"
        rules={[{ required: true, message: '请输入服务器名称' }]}
      >
        <Input placeholder="请输入名称" />
      </Form.Item>

      <Form.Item
        label="传输协议"
        name="transport"
        rules={[{ required: true, message: '请选择传输协议' }]}
      >
        <Select>
          <Select.Option value="sse">SSE</Select.Option>
          <Select.Option value="stdio">Stdio</Select.Option>
          <Select.Option value="streamablehttp">StreamableHTTP</Select.Option>
        </Select>
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit">添加服务器</Button>
      </Form.Item>
    </Form>
  );
}

Modal 弹窗

import { Modal, message } from 'antd';

function DeleteConfirm({ server, onConfirm }) {
  const handleDelete = () => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除服务器 "${server.name}" 吗?此操作不可恢复。`,
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        await onConfirm(server.name);
        message.success('删除成功');
      },
    });
  };

  return <Button danger onClick={handleDelete}>删除</Button>;
}

🤖 Ant Design X(AI 组件库)

Ant Design X 是 Ant Design 团队专门为 AI 对话场景打造的组件库。Kuai 前端使用它来构建 Agent 对话界面。

💡 Ant Design vs Ant Design X

Ant Design X 核心组件

组件作用使用场景
Bubble消息气泡显示用户消息和 AI 回复
Bubble.List消息列表对话历史滚动列表
Sender消息输入框用户输入消息的区域
ThoughtChain思考链展示 AI 的推理过程
Attachments附件组件文件上传和预览
Suggestion快捷建议预设的快捷问题按钮

Bubble 消息气泡

import { Bubble } from '@ant-design/x';

// 基本用法
<Bubble
  content="你好,我是 AI 助手!"
  placement="start"  // start=AI(左), end=用户(右)
/>

// 带头像和自定义内容
<Bubble
  content={messageContent}
  placement="start"
  avatar={{ src: '/ai-avatar.png' }}
  loading={isLoading}  // 加载中显示打字动画
/>

// 消息列表
<Bubble.List
  items={messages.map(msg => ({
    content: msg.text,
    placement: msg.role === 'user' ? 'end' : 'start',
    loading: msg.loading,
  }))}
/>

Sender 消息输入框

import { Sender } from '@ant-design/x';

function ChatInput({ onSend, loading }) {
  return (
    <Sender
      placeholder="输入消息..."
      loading={loading}
      onSubmit={(text) => onSend(text)}
      onCancel={() => {/* 取消正在生成的回复 */}}
    />
  );
}

ThoughtChain 思考链

import { ThoughtChain } from '@ant-design/x';

// 展示 AI 的思考/工具调用过程
<ThoughtChain
  items={[
    { title: '分析问题', status: 'success', description: '理解用户意图' },
    { title: '调用工具', status: 'success', description: '使用 MCP 工具获取数据' },
    { title: '生成回复', status: 'loading', description: '正在生成...' },
  ]}
/>

🏗️ 在 Kuai 中的实际使用

AgentChat 组件(核心对话组件)

Kuai 的 Agent 对话页面使用 AgentChat 组件,它同时使用了 antd 和 antd-x 的组件:

// src/components/common/AgentChat/index.jsx(简化)
'use client';

import { Button, Spin, message } from 'antd';           // antd 组件
import { Bubble, Sender, ThoughtChain } from '@ant-design/x';  // AI 组件
import styles from './AgentChat.module.css';              // CSS Modules

function AgentChat({ agentId }) {
  const [messages, setMessages] = useState([]);
  const [loading, setLoading] = useState(false);

  return (
    <div className={styles.chatContainer}>
      {/* 消息列表 — 使用 antd-x 的 Bubble.List */}
      <div className={styles.messageList}>
        <Bubble.List items={messages} />
      </div>

      {/* 输入区域 — 使用 antd-x 的 Sender */}
      <div className={styles.inputArea}>
        <Sender
          placeholder="输入消息..."
          loading={loading}
          onSubmit={handleSend}
        />
      </div>
    </div>
  );
}

💅 与 CSS Modules 配合

Kuai 前端使用 CSS Modules 进行样式隔离,而不是全局 CSS 或 CSS-in-JS。

CSS Modules 基本用法

/* AgentChat.module.css — 样式文件 */
.chatContainer {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.messageList {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
}

.inputArea {
  padding: 1rem;
  border-top: 1px solid #e7e5e4;
}
// 导入样式(styles 是一个对象,键是类名,值是编译后的唯一类名)
import styles from './AgentChat.module.css';

// 使用:styles.chatContainer 会被编译为类似 "AgentChat_chatContainer_a1b2c"
<div className={styles.chatContainer}>
  <div className={styles.messageList}>...</div>
  <div className={styles.inputArea}>...</div>
</div>

🔍 CSS Modules 的优势

CSS Modules 与 Ant Design 配合的注意事项

// ❌ 错误:不能用 CSS Modules 覆盖 antd 组件的内部类名
import styles from './MyComponent.module.css';
<Button className={styles.myButton}>点击</Button>
// styles.myButton 只能控制外层容器,不能直接修改 antd 内部的 .ant-btn 样式

// ✅ 正确方式 1:使用 antd 的 className + CSS Modules 的 :global
// MyComponent.module.css
// :global .ant-btn { font-size: 16px; }

// ✅ 正确方式 2:使用 antd 的 style prop
<Button style={{ fontSize: 16 }}>点击</Button>

// ✅ 正确方式 3:使用 antd 的 ConfigProvider 进行主题定制(推荐)

🎯 主题定制

ConfigProvider 全局主题

Ant Design 6 使用 ConfigProvider 进行全局主题定制,通过 theme 属性配置设计令牌(Design Token):

// src/app/providers.js 或根布局中
import { ConfigProvider } from 'antd';

function AppProviders({ children }) {
  return (
    <ConfigProvider
      theme={{
        token: {
          // 品牌色
          colorPrimary: '#b45309',      // 琥珀色(与课程主题一致)

          // 圆角
          borderRadius: 6,

          // 字体
          fontFamily: "'Noto Sans SC', -apple-system, sans-serif",

          // 字号
          fontSize: 14,
        },
        components: {
          // 组件级别的定制
          Menu: {
            itemSelectedBg: '#fef3c7',   // 菜单选中背景
            itemSelectedColor: '#b45309', // 菜单选中文字色
          },
          Table: {
            headerBg: '#f5f5f4',         // 表头背景色
          },
        },
      }}
    >
      {children}
    </ConfigProvider>
  );
}

Design Token 体系

层级说明示例
token全局种子令牌(影响所有组件)colorPrimary、borderRadius
components组件级别令牌(只影响特定组件)Menu.itemSelectedBg
algorithm主题算法(亮色/暗色/紧凑)theme.darkAlgorithm
// 使用暗色主题算法
import { ConfigProvider, theme } from 'antd';

<ConfigProvider
  theme={{
    algorithm: theme.darkAlgorithm,
    token: { colorPrimary: '#b45309' },
  }}
>
  {children}
</ConfigProvider>

✨ 图标使用

Ant Design 图标库 @ant-design/icons 提供了大量 SVG 图标,支持按需导入:

// 按需导入(只打包使用的图标)
import {
  HomeOutlined,
  SettingOutlined,
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  SearchOutlined,
  RobotOutlined,
} from '@ant-design/icons';

// 在组件中使用
<Button icon={<PlusOutlined />}>新建</Button>
<Menu.Item icon={<HomeOutlined />}>首页</Menu.Item>

⚠️ 图标导入注意事项

📱 响应式与布局技巧

Grid 栅格系统

import { Row, Col } from 'antd';

// 24 列栅格
<Row gutter={16}>
  <Col span={8}>  {/* 占 1/3 宽度 */}
    <Card>卡片 1</Card>
  </Col>
  <Col span={8}>
    <Card>卡片 2</Card>
  </Col>
  <Col span={8}>
    <Card>卡片 3</Card>
  </Col>
</Row>

// 响应式
<Row gutter={[16, 16]}>
  <Col xs={24} sm={12} md={8} lg={6}>
    <Card>自适应卡片</Card>
  </Col>
</Row>

Space 间距组件

import { Space, Button } from 'antd';

// 自动给子元素添加间距
<Space size="middle">
  <Button>取消</Button>
  <Button type="primary">确认</Button>
</Space>

// 带分隔线
<Space split={<Divider type="vertical" />}>
  <a>编辑</a>
  <a>删除</a>
</Space>

🧪 知识检验

题目 1:组件库选择

在 Kuai 前端中,构建 Agent 对话界面的 AI 消息气泡应该使用哪个库的组件?

A. Ant Design 6 的 Message 组件
B. Ant Design X 的 Bubble 组件
C. 自己用 div + CSS 手写
D. react-chat-widget 第三方库
答案 B。@ant-design/x(Ant Design X)是专门的 AI 对话组件库,其中 Bubble 组件专门用于显示消息气泡,支持用户消息(placement="end")和 AI 回复(placement="start"),还内置了加载动画。antd 的 Message 是全局提示(toast),用于操作反馈,不是对话气泡。

题目 2:CSS Modules

在 Kuai 前端中,为什么使用 import styles from './AgentChat.module.css' 而不是普通的 import './AgentChat.css'?

A. 只是命名习惯不同,没有实际区别
B. CSS Modules 会自动为类名添加唯一哈希后缀,避免样式冲突
C. 普通 CSS 在 Next.js 中不能使用
D. CSS Modules 的加载速度更快
答案 B。CSS Modules 的核心优势是样式隔离。当你写 .chatContainer { ... } 时,编译后会变成类似 AgentChat_chatContainer_a1b2c 的唯一类名。这样即使不同组件有同名类名也不会冲突。普通 CSS(全局 CSS)的类名是全局共享的,容易出现样式覆盖问题。

题目 3:主题定制

要将整个应用的主色调从默认蓝色改为橙色,最推荐的方式是什么?

A. 用 CSS 覆盖所有 antd 组件的 .ant-btn-primary 类名
B. 每个 Button 组件都加 style={{ background: 'orange' }}
C. 在根组件使用 ConfigProvider 的 theme.token.colorPrimary 配置
D. 修改 antd 的源码
答案 C。Ant Design 6 推荐使用 ConfigProvider 的 theme.token.colorPrimary 来设置主色调。这会自动影响所有使用主色的组件(Button、Link、Menu 选中态等),是一处配置、全局生效。用 CSS 覆盖容易遗漏且难维护,用 style 属性需要每个组件都写,修改源码更不可取。