@kwayteow/schema-antd-form
v0.0.1
Published
一个基于 Formily + Ant Design 的强大 Schema 表单组件库,提供开箱即用的表单解决方案。
Readme
@kwayteow/schema-antd-form
一个基于 Formily + Ant Design 的强大 Schema 表单组件库,提供开箱即用的表单解决方案。
✨ 特性
- 🚀 开箱即用 - 基于 JSON Schema 快速构建复杂表单
- 🎨 丰富组件 - 内置所有 Ant Design 表单组件
- 🔄 异步支持 - 完整的异步数据加载和字段联动
- 🎯 预设配置 - 多种表单布局和行为预设
- 🛡️ 类型安全 - 完整的 TypeScript 支持
- 🔧 高度可定制 - 灵活的配置和扩展能力
- 📱 响应式 - 支持多种屏幕尺寸
- 🌐 国际化 - 支持多语言
📦 安装
npm install @kwayteow/schema-antd-form
# 或
yarn add @kwayteow/schema-antd-form
# 或
pnpm add @kwayteow/schema-antd-form依赖要求
{
"react": ">=18.0.0",
"react-dom": ">=18.0.0",
"antd": ">=5.0.0",
"@formily/core": ">=2.3.0",
"@formily/react": ">=2.3.0"
}🚀 快速开始
基础用法
import React from "react";
import { SchemaForm } from "@kwayteow/schema-antd-form";
const App = () => {
const schema = {
type: "object",
properties: {
name: {
type: "string",
title: "姓名",
required: true,
"x-decorator": "FormItem",
"x-component": "Input",
},
email: {
type: "string",
title: "邮箱",
"x-decorator": "FormItem",
"x-component": "Input",
"x-validator": [{ format: "email" }],
},
submit: {
type: "void",
"x-component": "Submit",
"x-component-props": {
children: "提交",
},
},
},
};
return (
<SchemaForm
schema={schema}
events={{
onFormSubmitSuccess: (values) => {
console.log("提交成功:", values);
},
}}
/>
);
};使用预设配置
import { SchemaForm, createFormWithPreset } from "@kwayteow/schema-antd-form";
const LoginForm = () => {
const config = createFormWithPreset("login", {
events: {
onFormSubmitSuccess: (values) => {
console.log("登录成功:", values);
},
},
});
return <SchemaForm {...config} schema={loginSchema} />;
};API 集成
import { SchemaForm, HttpService } from "@kwayteow/schema-antd-form";
const FormWithAPI = () => {
const httpClient = new HttpService("https://api.example.com");
return (
<SchemaForm
schema={schema}
httpClient={httpClient}
api={{
url: "/users",
method: "POST",
}}
events={{
onFormSubmitSuccess: (result) => {
console.log("API 响应:", result);
},
onFormSubmitFailed: (error) => {
console.error("提交失败:", error);
},
}}
/>
);
};📚 核心概念
SchemaForm 组件
主要的表单组件,支持以下配置:
interface SchemaFormProps {
schema: Record<string, unknown>; // 表单 Schema 定义
ui?: UIConfig; // UI 配置
api?: RequestOptions | Function; // API 配置
httpClient?: HttpClient; // HTTP 客户端
events?: EventConfig; // 事件回调
lifecycle?: LifecycleConfig; // 生命周期
initialValues?: any; // 初始值
// ... 其他 Formily 配置
}UI 配置
支持多种布局和样式配置:
// 简单配置
const ui = {
layout: "horizontal",
size: "middle",
disabled: false,
};
// 完整配置
const ui = {
layout: "horizontal",
labelCol: { span: 6 },
wrapperCol: { span: 18 },
labelAlign: "right",
size: "large",
style: { padding: "20px" },
};预设配置
内置多种常用表单预设:
vertical- 垂直布局,适合移动端horizontal- 水平布局,适合桌面端inline- 内联布局,适合搜索表单compact- 紧凑布局,节省空间large- 大尺寸布局
import { uiPresets, createFormWithPreset } from '@kwayteow/schema-antd-form'
// 使用 UI 预设
<SchemaForm ui={uiPresets.horizontal} schema={schema} />
// 使用表单预设
const config = createFormWithPreset('login')
<SchemaForm {...config} schema={schema} />🔄 异步功能
异步数据源
import { updateAsyncDataSource } from "@kwayteow/schema-antd-form";
import { onFieldValueChange } from "@formily/core";
<SchemaForm
schema={schema}
effects={(form) => {
onFieldValueChange("province", async (field) => {
const cityField = form.query("city").take();
await updateAsyncDataSource(
cityField,
async (field) => {
const cities = await getCitiesByProvince(field.form.values.province);
return cities;
},
{
onSuccess: () => console.log("城市加载完成"),
onError: (error) => console.error("加载失败:", error),
}
);
});
}}
/>;异步字段联动
import { updateAsyncValue } from "@kwayteow/schema-antd-form";
// 用户信息自动填充
onFieldValueChange("userId", async (field) => {
await updateAsyncValue(field, async (field) => {
const userInfo = await getUserInfo(field.value);
// 自动填充其他字段
const nameField = form.query("name").take();
nameField.setValue(userInfo.name);
return userInfo;
});
});权限控制
import { updateAsyncFieldProps } from "@kwayteow/schema-antd-form";
// 根据角色控制字段权限
onFieldValueChange("role", async (field) => {
const sensitiveField = form.query("sensitiveData").take();
await updateAsyncFieldProps(sensitiveField, async (field) => {
const permission = await getPermission(field.form.values.role);
return {
required: permission.required,
disabled: permission.disabled,
};
});
});🛠️ 可用组件
表单组件
Input- 输入框Input.TextArea- 文本域Input.Password- 密码框InputNumber- 数字输入框Select- 选择器Checkbox- 复选框Radio- 单选框Switch- 开关DatePicker- 日期选择器TimePicker- 时间选择器Upload- 文件上传Rate- 评分Slider- 滑动输入条
布局组件
FormItem- 表单项FormLayout- 表单布局Submit- 提交按钮
🔧 异步函数 API
| 函数名 | 描述 | 用途 |
| ------------------------------ | ---------------- | -------------------- |
| updateAsyncDataSource | 异步更新数据源 | 下拉框选项、级联数据 |
| updateAsyncValue | 异步更新字段值 | 自动填充、计算值 |
| updateAsyncFieldProps | 异步更新字段属性 | 权限控制、动态验证 |
| updateAsyncComponentProps | 异步更新组件属性 | 动态样式、配置 |
| updateAsyncFieldLinkage | 异步字段联动 | 复杂联动逻辑 |
| updateAsyncConditionalRender | 异步条件渲染 | 动态显示/隐藏 |
| updateAsyncForm | 异步表单更新 | 整体状态变更 |
📖 高级用法
错误处理
<SchemaForm
schema={schema}
events={{
onFormSubmitFailed: (error) => {
switch (error.type) {
case "validation":
message.error("表单验证失败");
break;
case "network":
message.error("网络请求失败");
break;
case "business":
message.error(`业务错误: ${error.message}`);
break;
default:
message.error("未知错误");
}
},
}}
/>自定义 HTTP 客户端
import { HttpService } from '@kwayteow/schema-antd-form'
const customHttpClient = new HttpService('https://api.example.com', {
headers: {
'Authorization': 'Bearer your-token',
'X-API-Key': 'your-api-key',
},
timeout: 10000,
})
<SchemaForm httpClient={customHttpClient} />生命周期管理
<SchemaForm
schema={schema}
lifecycle={{
onFormMount: (values, form) => {
console.log("表单挂载");
},
onFormValuesChange: (values, form) => {
// 自动保存草稿
localStorage.setItem("draft", JSON.stringify(values));
},
}}
/>🎨 主题定制
组件完全兼容 Ant Design 的主题系统:
import { ConfigProvider } from "antd";
<ConfigProvider
theme={{
token: {
colorPrimary: "#1890ff",
},
}}
>
<SchemaForm schema={schema} />
</ConfigProvider>;📝 Schema 规范
基于 JSON Schema 标准,扩展了 Formily 的 x- 属性:
{
"type": "object",
"properties": {
"fieldName": {
"type": "string",
"title": "字段标题",
"description": "字段描述",
"required": true,
"x-decorator": "FormItem",
"x-component": "Input",
"x-component-props": {
"placeholder": "请输入"
},
"x-validator": [
{
"required": true,
"message": "此字段为必填项"
}
]
}
}
}🤝 贡献指南
我们欢迎所有形式的贡献!
开发环境
# 克隆项目
git clone https://github.com/kway-teow/schema-antd-form.git
# 安装依赖
npm install
# 启动开发服务器
npm run dev
# 启动文档
npm run doc提交规范
请遵循 Conventional Commits 规范:
feat: 添加新功能
fix: 修复问题
docs: 更新文档
style: 代码格式调整
refactor: 代码重构
test: 添加测试
chore: 构建过程或辅助工具的变动📄 许可证
🙏 致谢
- Formily - 强大的表单解决方案
- Ant Design - 优秀的 React UI 库
- React - 用于构建用户界面的 JavaScript 库
