joken-前端工程师

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::
  404 随笔 :: 39 文章 :: 8 评论 :: 20万 阅读

我将为你详细讲解如何在 Vite 项目中使用 Ant Design UI(简称 Antd),并结合 React 18 提供完整示例。Vite 是一个现代化的前端构建工具,相比 Create React App,它启动更快、支持按需加载更简单,非常适合搭配 Antd 开发高效的 React 应用。


1. 创建 Vite 项目

首先,使用 Vite 创建一个 React 项目。

步骤

  1. 初始化项目
    npm create vite@latest my-vite-antd-app --template react-ts
    cd my-vite-antd-app
    
    • --template react-ts:选择 React + TypeScript 模板。
  2. 安装依赖
    npm install
    
  3. 启动项目
    npm run dev
    
    • 默认在 http://localhost:5173 运行。

2. 安装 Ant Design

在 Vite 项目中添加 Antd。

步骤

  1. 安装 Antd
    npm install antd
    
  2. 基本使用
    • 修改 src/App.tsx
      import { Button } from 'antd';
      import 'antd/dist/reset.css'; // 全局引入样式
      
      const App = () => {
        return (
          <div style={{ padding: 20 }}>
            <h1>Vite + Ant Design</h1>
            <Button type="primary" onClick={() => alert('Hello Antd!')}>
              Click Me
            </Button>
          </div>
        );
      };
      
      export default App;
      
    • 运行后,你会看到一个蓝色按钮。

3. 配置按需加载(推荐)

Vite 原生支持按需加载,我们可以通过插件优化 Antd 的样式加载,避免全局引入全部 CSS。

步骤

  1. 安装插件
    npm install vite-plugin-style-import --save-dev
    npm install less --save-dev # Antd 5.x 使用 Less
    
  2. 配置 vite.config.ts
    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    import { StyleImport } from 'vite-plugin-style-import';
    
    export default defineConfig({
      plugins: [
        react(),
        StyleImport({
          libs: [
            {
              libraryName: 'antd',
              esModule: true,
              resolveStyle: (name) => `antd/es/${name}/style`,
            },
          ],
        }),
      ],
      css: {
        preprocessorOptions: {
          less: {
            javascriptEnabled: true, // 支持 Less 中的 JS 表达式
          },
        },
      },
    });
    
  3. 更新 src/App.tsx
    import { Button } from 'antd'; // 无需手动引入样式
    
    const App = () => {
      return (
        <div style={{ padding: 20 }}>
          <h1>Vite + Ant Design</h1>
          <Button type="primary">Click Me</Button>
        </div>
      );
    };
    
    export default App;
    
    • 样式会按需加载,只包含 Button 的 CSS。

4. 使用常见组件

以下是一个结合表单和表格的示例,展示 Antd 在 Vite 项目中的应用。

示例代码

// src/App.tsx
import { useState } from 'react';
import { Button, Form, Input, Table } from 'antd';

interface Item {
  key: string;
  name: string;
  age: string;
}

const App = () => {
  const [data, setData] = useState<Item[]>([]);
  const [form] = Form.useForm();

  const columns = [
    { title: '姓名', dataIndex: 'name', key: 'name' },
    { title: '年龄', dataIndex: 'age', key: 'age' },
  ];

  const onFinish = (values: { name: string; age: string }) => {
    setData([...data, { ...values, key: values.name }]);
    form.resetFields();
  };

  return (
    <div style={{ padding: 20 }}>
      <h1>Vite + Ant Design Demo</h1>
      <Form form={form} onFinish={onFinish} layout="inline">
        <Form.Item name="name" rules={[{ required: true, message: '请输入姓名' }]}>
          <Input placeholder="姓名" />
        </Form.Item>
        <Form.Item name="age" rules={[{ required: true, message: '请输入年龄' }]}>
          <Input placeholder="年龄" />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            添加
          </Button>
        </Form.Item>
      </Form>
      <Table dataSource={data} columns={columns} style={{ marginTop: 20 }} />
    </div>
  );
};

export default App;
  • 功能:输入姓名和年龄,提交后添加到表格。
  • 运行npm run dev,即可看到表单和表格交互。

5. 主题定制

Antd 支持静态和动态主题定制,以下是两种方法。

5.1 静态主题(构建时)

  1. 修改 vite.config.ts
    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    import { StyleImport } from 'vite-plugin-style-import';
    
    export default defineConfig({
      plugins: [
        react(),
        StyleImport({
          libs: [
            {
              libraryName: 'antd',
              esModule: true,
              resolveStyle: (name) => `antd/es/${name}/style`,
            },
          ],
        }),
      ],
      css: {
        preprocessorOptions: {
          less: {
            javascriptEnabled: true,
            modifyVars: {
              '@primary-color': '#1DA57A', // 修改主色为绿色
            },
          },
        },
      },
    });
    
  2. 效果:所有 Antd 组件的主色变为绿色。

5.2 动态主题(运行时)

import { Button, ConfigProvider } from 'antd';

const App = () => (
  <ConfigProvider theme={{ token: { colorPrimary: '#ff4d4f' } }}>
    <div style={{ padding: 20 }}>
      <h1>动态主题</h1>
      <Button type="primary">Red Button</Button>
    </div>
  </ConfigProvider>
);

export default App;
  • 效果:按钮变为红色,且只影响 ConfigProvider 包裹的组件。

6. 结合 React 18 并发特性

Vite 项目天然支持 React 18,以下是一个利用 startTransition 的示例。

示例代码

import { useState, startTransition } from 'react';
import { Button, Table } from 'antd';

const App = () => {
  const [data, setData] = useState<any[]>([]);

  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '名称', dataIndex: 'name', key: 'name' },
  ];

  const loadData = () => {
    startTransition(() => {
      const newData = Array(1000).fill(null).map((_, i) => ({
        id: i,
        name: `Item ${i}`,
      }));
      setData(newData); // 大数据分片渲染
    });
  };

  return (
    <div style={{ padding: 20 }}>
      <Button type="primary" onClick={loadData}>
        加载 1000 条数据
      </Button>
      <Table dataSource={data} columns={columns} rowKey="id" style={{ marginTop: 20 }} />
    </div>
  );
};

export default App;
  • 效果:点击按钮加载 1000 条数据,React 18 的 Fiber 架构分片渲染,避免阻塞主线程。

7. 注意事项

  • TypeScript 支持
    • Vite 默认支持 TS,确保组件类型正确,避免报错。
  • 插件版本
    • 使用 vite-plugin-style-import 时,确保与 Vite 版本兼容(推荐最新版)。
  • 性能优化
    • 按需加载是必须的,避免打包体积过大。
  • 文档参考

8. 项目结构参考

my-vite-antd-app/
├── src/
│   ├── App.tsx
│   ├── main.tsx
│   └── vite-env.d.ts
├── vite.config.ts
├── package.json
└── tsconfig.json

9. 总结

  • 初始化:用 Vite 创建 React + TS 项目。
  • 安装 Antdnpm install antd,并配置按需加载。
  • 使用组件:导入需要的 Antd 组件,按需加载样式。
  • 主题定制:通过 Less 或 ConfigProvider 修改样式。
  • React 18:结合并发特性提升性能。

Vite + Antd 是现代 React 开发的绝佳组合,启动快、配置简单,适合快速构建后台管理系统。如果需要更复杂的示例(如布局、路由),可以告诉我,我会进一步扩展!

posted on   joken1310  阅读(47)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示