程技 组件 KDesign 企业级 React UI 组件库 · 完整使用手册 Rich 2026-12-03 2026-12-03 KDesign 企业级 React UI 组件库 · 完整使用手册
面向”类金蝶云苍穹(Kingdee Cloud Cosmic)”企业级中后台 / 低代码平台开发
官方资料:react.kingdee.design · github.com/kingdee/kdesign 组件包:@kdcloudjs/kdesign · 当前版本:1.8.74 · 协议:Apache-2.0
目录
关于本手册
认知 KDesign
环境搭建与快速上手
全局配置 ConfigProvider
主题定制与品牌化
国际化
组件全解(按类别)
KWC:Web Components 跨框架方案
用 KDesign 构建”类金蝶云苍穹系统”——架构蓝图
页面级实现(登录/主页/导航/菜单/列表/详情/系统管理)
工程实践与最佳实践
常见问题 FAQ
附录:组件速查表 / 设计令牌 / 参考链接
第 0 章 关于本手册 金蝶云苍穹是金蝶的企业级 PaaS / 低代码平台,其前端体验由一套统一的设计系统 KDesign 驱动。KDesign of React 是把这套设计系统落地的 React 组件库。
本手册的目标有两层:
会用 KDesign :安装、配置、主题、国际化、60+ 组件的正确用法与 API 要点。
能搭苍穹 :把 KDesign 作为 UI 基座,组装出苍穹式的能力——顶部导航 + 可折叠左侧菜单 + 多页签工作台、元数据驱动的动态表单、带高级筛选的单据列表、详情抽屉、审批流、权限与多租户、报表看板。
重要认知:KDesign 是 UI 组件库,不是低代码引擎。 动态表单、流程引擎、元数据服务、权限中心需要你在 KDesign 之上自行构建(或对接 Formily / 自研渲染器)。本手册第 8 章给出可落地的架构与代码骨架。
第 1 章 认知 KDesign 1.1 定位与特性
提炼自金蝶企业级中后台产品的交互语言与视觉风格(设计语言代号 Flower )。
开箱即用的丰富企业级 React 组件(当前覆盖 基础 / 布局 / 导航 / 表单 / 展示 / 反馈 / 筛选 七大类约 60+ 组件)。
TypeScript 开发 ,提供完整类型定义(lib/index.d.ts)。
全键盘支持 :组件可纯键盘操作,适合高密度的数据录入场景(苍穹式快速录单)。
国际化 :通过 ConfigProvider 注入语言包。
全面的主题化定制 :基于 Less 变量 + CSS 变量,可换肤、换主题色、换图标前缀。
按需加载 :基于 ES Modules 的 tree shaking,直接 import { Button } 即可。
1.2 技术栈与版本
项
说明
包名
@kdcloudjs/kdesign
版本
1.8.74
React 要求
peerDependencies: react >=16.9.0, react-dom >=16.9.0
推荐 React
16.14 / 17.x(官方浏览器示例用 16.14.0);React 18 经 createRoot 一般可用,但需自测
样式方案
Less + CSS 变量(css-vars-ponyfill 兼容旧浏览器)
表单校验
async-validator(与 Element / Antd 同源方案)
表格内核
@kdcloudjs/table(金蝶自研高性能表格)
图标
@kdcloudjs/kdesign-icons,默认前缀 kdicon
其他关键依赖
popperjs / react-popper(浮层)、big.js(高精度数值)、date-fns(日期)、styled-components@5、lodash、classnames
浏览器兼容
现代浏览器 + IE11 (browserslist 含 ie >= 11)
产物
dist(UMD)、lib(CommonJS)、es(ESM),均带 style/*.less
1.3 包结构与引入方式 1 2 3 npm install @kdcloudjs/kdesign --save yarn add @kdcloudjs/kdesign
ESM / CJS (推荐,支持按需加载):1 2 import { Button } from '@kdcloudjs/kdesign' import '@kdcloudjs/kdesign/dist/kdesign.css'
UMD(浏览器直接引入) :使用全局变量 kdesign,引入 dist/kdesign.min.js 与 dist/kdesign.min.css。
1.4 与 Ant Design 的关键差异(苍穹迁移者必读)
维度
KDesign
Ant Design
表格列字段键
columns[].code
columns[].dataIndex
默认输入框风格
borderType: 'underline'(线型,苍穹风)
边框型
全局配置
ConfigProvider(context,value 属性)
ConfigProvider(<ConfigProvider> 子节点)
主题变量语言
Less(@theme-color 等)
Less(@primary-color 等)
表单校验
async-validator
async-validator
设计语言
Flower(金蝶)
Ant Design
第 2 章 环境搭建与快速上手 2.1 脚手架选型
场景
方案
快速验证 / 中小项目
Create React App(CRA)+ craco
现代工程 / Vite 用户
Vite + vite-plugin-imp(或手动按需)
大型微前端
自建 Webpack + less-loader + babel-plugin-import(如需要)
注意:KDesign 默认已支持 tree shaking,直接 import 即可按需。若需 定制 Less 主题 ,必须让 less-loader 处理 node_modules/@kdcloudjs/kdesign 下的样式(不要被 webpack 的 exclude: /node_modules/ 过滤掉)。
2.2 CRA 集成(含主题定制) 1 2 3 4 npx create-react-app cosmic-demo --template typescript cd cosmic-demoyarn add @kdcloudjs/kdesign yarn add -D @craco/craco craco-less
package.json 脚本改为 craco:
1 2 3 4 5 6 "scripts": { - "start": "react-scripts start", - "build": "react-scripts build", + "start": "craco start", + "build": "craco build", }
craco.config.js(定制苍穹蓝主题):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 const CracoLessPlugin = require ('craco-less' )module .exports = { plugins : [{ plugin : CracoLessPlugin , options : { lessLoaderOptions : { lessOptions : { modifyVars : { 'theme-color' : '#1f5fff' , 'success-color' : '#1ba854' , 'radius-size' : '3px' , }, javascriptEnabled : true , }, }, }, }], }
src/App.tsx:
1 2 3 4 5 6 7 8 9 10 import React from 'react' import { Button } from '@kdcloudjs/kdesign' import '@kdcloudjs/kdesign/dist/kdesign.css' const App : React .FC = () => ( <div > <Button type ="primary" > KDesign 按钮</Button > </div > ) export default App
若使用主题定制,把 @kdcloudjs/kdesign/dist/kdesign.css 换成 @kdcloudjs/kdesign/dist/kdesign.less,并在 less 入口里 @import。
2.3 第一个应用(含 ConfigProvider 外壳) 1 2 3 4 5 6 7 8 9 10 import React from 'react' import { Button , ConfigProvider } from '@kdcloudjs/kdesign' import '@kdcloudjs/kdesign/dist/kdesign.css' const App : React .FC = () => ( <ConfigProvider value ={{ compDefaultProps: { Input: { borderType: 'bordered ' } } }}> <Button type ="primary" > 提交</Button > </ConfigProvider > ) export default App
2.4 浏览器(UMD)引入 1 2 3 4 5 6 7 <script src ="https://unpkg.com/react@16/umd/react.development.js" > </script > <script src ="https://unpkg.com/react-dom@16/umd/react-dom.development.js" > </script > <script src ="https://unpkg.com/@kdcloudjs/kdesign/dist/kdesign.min.js" > </script > <link rel ="stylesheet" href ="https://unpkg.com/@kdcloudjs/kdesign/dist/kdesign.min.css" > <script > ReactDOM .render (<kdesign.Button type ="primary" > 按钮</kdesign.Button > , document .getElementById ('root' )) </script >
第 3 章 全局配置 ConfigProvider ConfigProvider 用 React Context 包裹一次即全应用生效,可用于:统一组件默认属性、注入语言包、切换主题 / 方向 / 前缀。
3.1 基本用法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import { ConfigProvider } from '@kdcloudjs/kdesign' const myConfig = { compDefaultProps : { Input : { borderType : 'bordered' }, Form : { layout : 'vertical' }, Button : { size : 'middle' }, }, } export default () => ( <ConfigProvider value ={myConfig} > <App /> </ConfigProvider > )
3.2 value 配置项
字段
作用
compDefaultProps
覆盖任意组件的默认 props(见 3.3 全量清单)
localeConfig.localeData
注入语言包(import zhCN from '@kdcloudjs/kdesign/lib/locale/zh-CN')
theme
主题对象(配合 CSS 变量换肤)
prefixCls
样式前缀(多套 UI 库共存时避免类名冲突)
direction
ltr / rtl
size
全局尺寸(组件自身 size 优先)
3.3 全量组件默认属性清单(来自官方)
在 compDefaultProps 中按组件名覆写即可。以下为企业级最常用的默认值(节选核心):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 const compDefaultProps = { Alert : { type : 'warning' , showIcon : false , closable : false , delayOffTime : 5000 , banner : false }, Button : { type : 'second' , iconPlace : 'left' , size : 'middle' , bordered : true }, Card : { hoverable : false , selectable : false }, Cascader : { allowClear : true , expandTrigger : 'click' , notFoundContent : 'No Data' , fieldNames : { label : 'label' , value : 'value' , children : 'children' } }, Checkbox : { defaultChecked : false , checkboxType : 'default' , size : 'middle' }, DatePicker :{ allowClear : true , borderType : 'underline' , picker : 'date' , size : 'middle' , showToday : false , yearItemNumber : 15 }, Drawer : { closable : true , maskClosable : true , placement : 'right' , width : 365 , zIndex : 1050 }, Form : { layout : 'vertical' , labelAlign : 'left' , size : 'middle' }, Input : { type : 'text' , size : 'middle' , borderType : 'underline' }, Select : { size : 'middle' , borderType : 'underline' , mode : 'single' }, InputNumber :{ size : 'middle' , borderType : 'underline' , zeroShow : false , mustInPrecisionScope : true }, Menu : { mode : 'vertical' , inlineIndent : 50 , theme : 'dark' , collapsed : false }, Modal : { type : 'normal' , keyboard : true , maskClosable : true , width : 460 , height : 340 , draggable : true , showline : true }, Pagination :{ total : 0 , pageType : 'basic' , defaultCurrent : 1 , defaultPageSize : 10 , pageSizeOptions : [10 , 20 , 50 , 100 ] }, Popconfirm : { placement : 'top' , trigger : 'click' , okType : 'primary' }, Progress : { type : 'line' , percent : 0 , showInfo : true }, Radio : { checked : false , defaultChecked : false }, Row : { align : 'top' , gutter : 12 , justify : 'start' , wrap : true }, Space : { direction : 'horizontal' , size : 'small' , align : 'center' }, SplitPanel :{ defaultSplit : 0.5 , mode : 'horizontal' , canFold : true }, Spin : { type : 'page' , spinning : true }, Table : { }, Tabs : { type : 'line' , size : 'middle' }, Tag : { type : 'status' , size : 'middle' }, Tree : { virtual : true , defaultExpandAll : false }, Upload : { multiple : false , method : 'post' , name : 'file' , listType : 'text' }, }
苍穹风格统一设定建议:把 Input / Select / InputNumber / DatePicker / TextArea / Search 全部设为 borderType: 'bordered' 或统一 underline,保持录入控件视觉一致。
第 4 章 主题定制与品牌化 KDesign 样式基于 Less ,定义了一套全局 / 组件级变量。定制原理是 less 的 modifyVars 覆盖变量。
4.1 全局样式变量(核心清单) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 @theme-color: #5582f3 ; @theme-color-level1 ..9 : ...; @theme-color-disabled / -hover / -click / -active-light / -active-dark@success-color : #1ba854 ; @success-bg-color: #f2fff5 ; @success-border-color: #6dd18e ;@warning-color: #ff991c ; @warning-bg-color: #fffbf2 ; @warning-border-color: #ffcb78 ;@error-color: #fb2323 ; @error-bg-color: #fff2f4 ; @error-border-color: #ff8088 ;@ongoing-color: #276ff5 ; @ongoing-bg-color: #f2f9ff ; @ongoing-border-color: #85b8ff ;@disabled-color: #b2b2b2 ; @disabled-border-color: #ccc ;@link-color: #0e5fd8 ; @link-color-hover: #3987ed ; @link-color-active: #0041b0 ;@primary-text-color: #212121 ; @secondary-text-color: #666 ; @third-text-color: #999 ; @placeholder-text-color: #ccc ;@bg: #fff ; @bg2: #f2f2f2 ; @contain-bg: #fafafa ;@radius-size: 2px ; @input-color: #999 ;@strong-border-color: #d9d9d9 ;@weak-border-color: #e5e5e5 ;
完整变量见官方仓库 components/style/themes/default.less。
1 2 3 4 5 6 @btn-primary-background-color: @theme-color ;@btn-primary-border-color: @theme-color ;@btn-second-font-color: rgba (@secondary-text-color , 65% );@btn-danger-background-color: @error-color ;@btn-small-height: 24px ; @btn-middle-height: 28px ; @btn-large-height: 32px ;@btn-transition-fn: cubic-bezier (0.075 , 0.82 , 0.165 , 1 );
4.3 三种定制方式 方式 A:webpack / less-loader 的 modifyVars(最常用,见 2.2)
1 2 lessOptions : { modifyVars : { 'theme-color' : '#1f5fff' , 'radius-size' : '3px' }, javascriptEnabled : true }
方式 B:独立 Less 变量文件覆盖
1 2 3 4 5 @import '~@kdcloudjs/kdesign/lib/style/themes/default.less' ;@theme-color: #1f5fff ;@radius-size: 3px ;
方式 C:运行时 CSS 变量换肤(多租户 / 主题切换) KDesign 通过 css-vars-ponyfill 注入 CSS 变量,可在运行时动态改 :root 变量实现”换肤不刷新”,适合苍穹式多租户品牌色。
4.4 苍穹科技蓝主题示例 1 2 3 4 5 6 7 8 @theme-color: #1f5fff ;@success-color: #00b96b ;@error-color: #f5222d ;@warning-color: #fa8c16 ;@radius-size: 3px ;@strong-border-color: #e0e4ea ;@weak-border-color: #eef0f3 ;
第 5 章 国际化 默认文案为中文。切换语言用 ConfigProvider 的 localeConfig:
1 2 3 4 5 6 import zhCN from '@kdcloudjs/kdesign/lib/locale/zh-CN' import { ConfigProvider } from '@kdcloudjs/kdesign' <ConfigProvider value={{ localeConfig : { localeData : zhCN } }}> <App /> </ConfigProvider >
5.1 语言包字段(节选) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 const locale = { locale : 'zh-CN' , 'DatePicker.placeholder' : '请选择日期' , 'DatePicker.now' : '此刻' , 'DatePicker.today' : '今天' , 'global.selectholder' : '请选择' , 'global.placeholder' : '请输入...' , 'global.cancel' : '取消' , 'global.confirm' : '确定' , 'Pagination.total' : '共{page}页{row}条' , 'Modal.okText' : '确定' , 'Modal.cancelText' : '取消' , 'Empty.emptyText' : '暂无数据' , 'Filter.filter' : '过滤' , 'Filter.scheme' : '方案' , 'Filter.query' : '查询' , 'Search.placeholder' : '请输入需要搜索的内容' , 'Transfer.selectAll' : '全选' , }
5.2 新增语言包 找不到所需语言时,复制 zh-CN.tsx 翻译成新语言(如 en-US.tsx),把字段值替换为目标语言,再经 ConfigProvider 注入,并可向官方提 PR。
第 6 章 组件全解(按类别)
约定:所有组件均从 @kdcloudjs/kdesign 导入。每个组件给出”用途 + 关键 API + 片段”。完整 API 以官网 /components/<name> 为准。
6.1 基础(Basic)
组件
关键 API
说明
Button
type: primary/second/ghost/link/danger、bordered、size: small/middle/large、iconPlace
苍穹主操作为 type="primary"
Icon
type、prefix(默认 kdicon)、spin
图标库 @kdcloudjs/kdesign-icons
SVGIcon
同上,SVG 版
高清场景
Link
href、disabled、target
链接
Typography
type: title/paragraph、level
文本层级
Pagination
total、pageType、current、pageSize、pageSizeOptions:[10,20,50,100]、showTitle
分页器(Table 内置)
QRCode
value、size、color
二维码(1.8.x 新增)
Clipboard
text、onCopy
一键复制
1 2 <Button type ="primary" bordered>保存</Button > <Button type ="danger" > 删除</Button >
6.2 布局(Layout)
组件
关键 API
说明
Layout
容器,可嵌套
整体布局
Header
—
顶栏
Sider
collapsed、collapsible、collapsedWidth、breakpoint、trigger={null}(自定义触发器)、theme
苍穹左侧菜单容器
Content
—
内容区
Footer
—
底栏
Grid
Row(gutter/align/justify/wrap)、Col(span/offset)
24 栅格
Space
direction、size、align
间距
Divider
type: horizontal/vertical、orientation
分割线
SplitPanel
mode、defaultSplit、min、max、canFold
左右/上下分隔(列表+详情常用)
1 2 3 4 5 6 7 <Layout > <Header > 顶栏</Header > <Layout > <Sider collapsible breakpoint ="lg" > 菜单</Sider > <Content > 页面</Content > </Layout > </Layout >
6.3 导航(Navigation)
组件
关键 API
说明
Menu
mode: vertical/horizontal/inline、theme: dark/light、inlineIndent、collapsed、selectedKeys、openKeys;子项 MenuItem/MenuSubMenu
系统导航,结合路由
Tabs
type: line/card、size、activeKey、onChange;TabPane(tab、key)
苍穹多页签工作台核心
Breadcrumb
separator;Breadcrumb.Item
面包屑
Dropdown
trigger: hover/click、placement、overlay
下拉菜单
Steps
direction、current、labelPlacement;Step
向导 / 审批流步骤
Tree
treeData、checkable、defaultExpandAll、virtual、switcherIcon
组织架构 / 分类树
Anchor
type: bookmarks、affix
锚点
1 2 3 4 5 6 <Menu mode="inline" theme="dark" selectedKeys={['dashboard' ]}> <MenuItem key ="dashboard" > 工作台</MenuItem > <MenuSubMenu key ="bd" title ="基础资料" > <MenuItem key ="bd-supplier" > 供应商</MenuItem > </MenuSubMenu > </Menu >
KDesign 自带 Form + Form.Item,校验基于 async-validator。
属性
类型
说明
form
Form.useForm() 实例
受控表单实例
layout
vertical/horizontal/inline
布局(默认 vertical)
labelAlign
left/right
标签对齐
name
string
表单名
onFinish(values)
fn
校验通过提交
onFinishFailed({values,errorFields})
fn
校验失败
onValuesChange({changedValues,allValues})
fn
值变化
disabled
boolean
整体禁用
defaultValue
{name: value}
初始默认值
属性
说明
name
字段名(对应 values[name])
label
标签
required
是否必录
rules
Rule[](async-validator 规则)
hidden
隐藏
labelWidth / wrappedWidth
宽度
extra
额外提示
syncValueTrigger
自定义同步值事件(1.8.45+)
validateTrigger
校验时机(默认 onchange)
valuePropName
子节点值属性(如 Switch 用 checked)
getFieldsValue / getFieldValue / setFieldsValue / setFieldValue / validateFields() / resetFields() / submit() / getFieldError / getFieldsError。
示例:登录 + 校验 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import { Form , Input , Button , Message } from '@kdcloudjs/kdesign' const Demo : React .FC = () => { const [form] = Form .useForm () const onFinish = (values : any ) => Message .success ('提交: ' + JSON .stringify (values)) return ( <Form form ={form} layout ="vertical" onFinish ={onFinish} > <Form.Item name ="username" label ="用户名" required rules ={[{ required: true , message: '请输入用户名 ' }]}> <Input placeholder ="请输入..." /> </Form.Item > <Form.Item name ="password" label ="密码" required rules ={[{ required: true , message: '请输入密码 ' }]}> <Input type ="password" /> </Form.Item > <Button type ="primary" htmlType ="submit" > 登录</Button > </Form > ) }
录入控件速查
控件
关键 API
苍穹用途
Input
type、borderType、maxLength、allowClear
文本
TextArea
autoSize、maxLength、canResize
多行/备注
InputNumber
min/max、precision、borderType、zeroShow
数值/金额(big.js 高精度)
Select
mode: single/multiple/tags、showSearch、options、fieldNames
下拉 / 多选
Cascader
options、expandTrigger、fieldNames
级联(省市区)
TreeSelect
treeData、treeCheckable
树选择
DatePicker
picker: date/week/month/quarter/year、showTime、format
日期
RangePicker
picker、separator
日期区间
Checkbox / CheckboxGroup
checkboxType
多选
Radio / RadioGroup
value、options
单选
Switch
size、checked、loading
布尔开关
Slider
min/max/step、range
区间
Rate
count、allowHalf
评分
Transfer
dataSource、titles、showSearch
穿梭(分配权限)
Upload
action、multiple、listType、beforeUpload
附件
ColorPicker
value、onChange
颜色
CityPicker
国内/国际/常用
城市
GeoZonePicker
—
行政区划
Signature
—
手写签名
ImageCropper
—
图片裁剪
Stepper
step、borderType
步进
BaseData
dataSource / 远程基础资料
苍穹核心:基础资料选择(供应商/客户/物料)
6.5 展示(Display)—— Table 重点 Table 关键 API(注意 code 而非 dataIndex)
属性
说明
dataSource
数据数组
columns
列定义;字段键用 code (非 dataIndex),表头用 name
primaryKey
行主键字段(开启行选择必须)
rowSelection
{ type: checkbox/radio, selectedRowKeys, onChange }
pagination
分页配置(或直接用 Pagination)
filter / filters / defaultFilters / onFilterChanged
过滤(列 filterable)
sort / sorts / defaultSortOrder / onChangeSorts
排序(列 sortable)
scroll
固定宽高 / 虚拟滚动
expandable
展开行
bordered
边框
列定义示例:
1 2 3 4 5 6 7 8 9 10 11 const columns = [ { code : 'No' , name : '序号' , width : 60 , align : 'center' }, { code : 'order' , name : '单据号' , width : 200 }, { code : 'from' , name : '来户' , width : 200 }, { code : 'amount' , name : '应付金额' , width : 120 , align : 'right' }, ] const dataSource = [ { id : '1' , No : 1 , order : 'AP-202009-00001' , from : '陕西环宇科技' , amount : '26,800.00' }, ] <Table dataSource={dataSource} columns={columns} primaryKey="id" rowSelection={{ type : 'checkbox' }} />
坑:KDesign Table 用 code 映射字段,从 Antd 迁移时务必把 dataIndex 改成 code。
其他展示组件:
组件
说明
Card
卡片(hoverable、selectable)
Drawer
抽屉详情(placement、width、maskClosable、destroyOnClose)
Modal
弹窗(type、draggable、footerBtnOrder、width/height)
Tag
状态标签(type: status、color)
Badge
徽标数
Avatar
头像
Image
图片(preview)
Carousel
走马灯
Collapse
折叠面板
Timeline
时间轴(审批轨迹)
SplitPanel
分割容器(见 6.2)
6.6 反馈(Feedback)
组件
关键 API
说明
Message
Message.success/error/warning(info)
轻提示(命令式)
Notification
Notification.open({...})
通知
Modal
Modal.confirm/info
确认框
Alert
type、showIcon、closable、banner
警告条
Popconfirm
title、onConfirm、placement
气泡确认(删除前)
Tooltip
title、placement、trigger
文字提示
Progress
type: line/circle、percent
进度
Spin
spinning、type: page/chunk
加载
Empty
emptyText
空状态
1 2 3 Message .success ('保存成功' )Modal .confirm ({ title : '确认提交?' , onOk : submit })<Popconfirm title="确认删除?" onConfirm={del}><Button > 删除</Button > </Popconfirm >
6.7 筛选(Filter / Search)—— 苍穹列表栏核心 Filter 是 KDesign 特色的企业级查询栏组件:把”筛选条件 + 常用方案 + 高级查询”做成一个整体。
属性
说明
fields
条件字段配置数组
schemes
已保存查询方案
defaultTabKey
'condition'(条件)
1 2 3 4 5 6 7 8 9 const fields = [ { name : 'billNo' , label : '单据编号' , type : 'input' }, { name : 'supplier' , label : '供应商' , type : 'select' , options : [...] }, { name : 'date' , label : '单据日期' , type : 'daterange' }, ] const schemes = [{ key : 'mine' , name : '我负责的' , filters : { } }]<Filter fields={fields} schemes={schemes} onQuery={(values ) => loadList (values)} />
Search:顶部智能搜索框(placeholder、desc、nplDesc 智能搜索提示)。
第 7 章 KWC(Web Components 跨框架方案) 7.1 是什么 KWC(KDesign Web Components) 把 KDesign React 组件封装成标准 Custom Elements(Web Components) ,使得 Vue / Angular / 原生 JS / 低代码设计器 也能直接使用 KDesign 的视觉与交互,无需引入 React 运行时耦合。
价值场景(苍穹类平台):
低代码设计器渲染的组件要在不同技术栈宿主里运行;
微前端中子应用用 Vue、主应用用 React,共享同一套 KDesign 视觉;
平台方(金蝶内网)以”工程包 + 文档包”分发给业务同事共创自定义控件。
7.2 工程结构(内网共创模板) 1 2 3 4 5 6 7 8 9 10 11 kd-custom-control-template-for-kwc/ ├─ build/ webpack 通用/开发/生产配置 ├─ src/ │ ├─ modules/x/ 模块 │ │ └─ app/ app.css / app.html / app.js(组件三件套) │ │ └─ utils/ kwc-shadow-injector.js │ ├─ devIndex.js 开发入口 │ └─ index.js 生产入口 ├─ static/lang/zh_CN.json 多语言词条 ├─ kwc.config.json KWC 配置 └─ package.json
本地开发:npm run dev → 访问 localhost:8000。Node 推荐 v18.20.8+ (Win10+)。
7.3 使用形态(示意) 1 2 3 4 <script src ="/kd-kwc.bundle.js" > </script > <kd-button type ="primary" > 提交</kd-button > <kd-table data-source ="..." columns ="..." > </kd-table >
说明:KWC 的具体 npm 包名与版本以金蝶官方 release 为准(官方仓库 kwc / kwcdocs 目录)。对外开源版本若未发布,可基于 KDesign React 自行用 Stencil / Lit 封装等价 Web Components。
7.4 微前端建议 苍穹式平台主框架用 KDesign React + qiankun;子应用若技术栈不同,用 KWC 提供的 Web Components 保证视觉一致,避免多套 UI 库样式冲突(必要时用 ConfigProvider 的 prefixCls 隔离)。
第 8 章 用 KDesign 构建”类金蝶云苍穹系统”——架构蓝图
金蝶云苍穹本质是 元数据驱动的低代码 PaaS 。KDesign 解决”看起来像苍穹、用起来像苍穹”,下面给出可落地的端到端方案。
8.1 苍穹能力拆解 → KDesign 对应
苍穹能力
KDesign 落点
统一门户 / 工作台
Layout + Header + Sider(Menu) + Tabs(多页签) + Breadcrumb
动态表单(元数据驱动)
Form + 各录入控件 + 自研 Schema→组件 渲染器
单据 / 列表页
Table + Filter + Search + Pagination + Tag + 操作列
详情 / 编辑
Drawer + Modal + Tabs + Descriptions(自封装)
审批流 / 流程
Steps + Timeline + Tag(状态) + Modal(审批意见)
基础资料
BaseData / TreeSelect / Select(远程数据源)
组织 / 权限
Menu 动态渲染 + 按钮级权限 + Transfer(分配)
多租户 / 品牌
ConfigProvider + 主题切换(CSS 变量)
报表 / BI 看板
Card + Table + 自接 ECharts / AntV(KDesign 不含图表)
移动端
KDesign 响应式 + KWC(或独立 H5)
8.2 整体技术架构 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ┌──────────────────────────── 前端(React + KDesign) ────────────────────────────┐ │ AppShell(Layout/Header/Sider/Tabs) │ │ ├─ 路由(react-router) → 页面组件 │ │ ├─ 状态(zustand/redux): 用户/租户/打开页签/权限 │ │ ├─ 动态表单引擎: Schema → KDesign Form.Item 渲染器 │ │ ├─ ProTable 封装: Table + Filter + Pagination 二开组件 │ │ └─ 请求层(axios): 统一拦截、错误用 Message/Notification │ └──────────────────────────────────┬──────────────────────────────────────────────┘ │ REST / GraphQL ┌──────────────────────────────────▼──────────────────────────────────────────────┐ │ 后端(微服务) │ │ ├─ 元数据服务: form_id → Schema(render 接口) │ │ ├─ 业务服务: CRUD / 提交(submit 接口) │ │ ├─ 流程引擎: 任务 → form_id + 初始值 │ │ ├─ 权限/组织: 菜单树、角色、数据权限 │ │ └─ 租户: 主题/品牌配置 │ └──────────────────────────────────────────────────────────────────────────────────┘
8.3 应用骨架(苍穹式”顶栏 + 折叠左菜单 + 多页签”) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 import React , { useState } from 'react' import { Layout , Menu , Tabs , Breadcrumb , Button } from '@kdcloudjs/kdesign' import { useLocation, useNavigate, Route , Routes } from 'react-router-dom' const { Header , Sider , Content } = Layout const menuData = [ { key : 'dashboard' , label : '工作台' }, { key : 'bd' , label : '基础资料' , children : [ { key : 'bd-supplier' , label : '供应商' }, { key : 'bd-material' , label : '物料' }, ]}, { key : 'po' , label : '采购订单' }, ] export const AppShell : React .FC = () => { const [collapsed, setCollapsed] = useState (false ) const [tabs, setTabs] = useState ([{ key : 'dashboard' , title : '工作台' }]) const [active, setActive] = useState ('dashboard' ) const navigate = useNavigate () const openTab = (key : string , title : string ) => { if (!tabs.find (t => t.key === key)) setTabs ([...tabs, { key, title }]) setActive (key); navigate ('/' + key) } return ( <Layout style ={{ height: '100vh ' }}> <Header style ={{ display: 'flex ', alignItems: 'center ', background: '#001529 ', color: '#fff ' }}> <span style ={{ fontWeight: 700 , marginRight: 24 }}> Cosmic · 企业云</span > <span style ={{ flex: 1 }}> 全局搜索 <Input placeholder ="搜索单据/客户..." style ={{ width: 260 }} /> </span > <Button type ="link" > 管理员</Button > </Header > <Layout > <Sider collapsible collapsed ={collapsed} onCollapse ={setCollapsed} theme ="dark" width ={220} > <Menu mode ="inline" theme ="dark" selectedKeys ={[active]} onClick ={({ key }) => openTab(key, key)}> {menuData.map(renderMenu)} </Menu > </Sider > <Content style ={{ padding: 12 , background: '#f2f2f2 ' }}> <Tabs type ="card" activeKey ={active} onChange ={setActive} onEdit ={(key, action ) => action === 'remove' && setTabs(tabs.filter(t => t.key !== key))}> {tabs.map(t => <Tabs.TabPane tab ={t.title} key ={t.key} > <Routes > <Route path ={ '/' + t.key } element ={ <PagePlaceholder name ={t.title} /> } /> </Routes > </Tabs.TabPane > )} </Tabs > </Content > </Layout > </Layout > ) }
8.4 动态表单引擎(元数据驱动) KDesign Form 是声明式静态表单;苍穹是元数据驱动的动态表单 。做法:定义 JSON Schema → 写一个渲染器把字段映射成 KDesign 控件。
Schema 示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 { "formId" : "purchase_order" , "title" : "采购订单" , "fields" : [ { "name" : "bill_no" , "label" : "单据编号" , "type" : "input" , "required" : true } , { "name" : "supplier" , "label" : "供应商" , "type" : "basedata" , "required" : true , "dataSource" : "/api/bd/supplier" } , { "name" : "bill_date" , "label" : "单据日期" , "type" : "date" } , { "name" : "amount" , "label" : "金额" , "type" : "number" , "precision" : 2 } , { "name" : "status" , "label" : "状态" , "type" : "select" , "options" : [ { "label" : "草稿" , "value" : "draft" } , { "label" : "已提交" , "value" : "submitted" } ] } , { "name" : "remark" , "label" : "备注" , "type" : "textarea" } , { "name" : "attachment" , "label" : "附件" , "type" : "upload" } ] }
字段类型 → KDesign 组件映射表:
schema.type
KDesign 组件
input
Input
textarea
TextArea
number
InputNumber(precision)
date / datetime
DatePicker(showTime)
daterange
RangePicker
select
Select(options)
multiselect
Select mode="multiple"
bool
Switch(valuePropName="checked")
enum/radio
RadioGroup
checkbox
CheckboxGroup
cascader
Cascader
tree
TreeSelect
basedata
BaseData(dataSource 远程)
upload
Upload
rate
Rate
渲染器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 import { Form , Input , InputNumber , Select , DatePicker , Switch , TextArea , Upload , BaseData } from '@kdcloudjs/kdesign' const Widget : React .FC <{ field : any }> = ({ field } ) => { switch (field.type ) { case 'input' : return <Input placeholder ={field.label} /> case 'textarea' : return <TextArea /> case 'number' : return <InputNumber precision ={field.precision} /> case 'date' : return <DatePicker /> case 'select' : return <Select options ={field.options} /> case 'bool' : return <Switch /> case 'basedata' : return <BaseData dataSource ={field.dataSource} /> case 'upload' : return <Upload action ="/api/upload" /> default : return <Input /> } } export const DynamicForm : React .FC <{ schema : any ; initial ?: any }> = ({ schema, initial } ) => { const [form] = Form .useForm () return ( <Form form ={form} layout ="vertical" initialValues ={initial} onFinish ={(v) => submitForm(schema.formId, v)}> {schema.fields.map((f: any) => ( <Form.Item key ={f.name} name ={f.name} label ={f.label} required ={f.required} rules ={f.required ? [{ required: true , message: `请录入 ${f.label }` }] : []}> <Widget field ={f} /> </Form.Item > ))} <Button type ="primary" htmlType ="submit" > 保存</Button > </Form > ) }
进阶:把 Widget 抽成 widgetRegistry,支持自定义组件与联动(x-reactions 思路),即可逼近苍穹表单设计器。
8.5 单据 / 列表页(ProTable 封装) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 import { Table , Filter , Button , Tag , Space } from '@kdcloudjs/kdesign' export const ProTable : React .FC <{ columns : any []; fetch : (q : any ) => Promise <any []> }> = ({ columns, fetch } ) => { const [data, setData] = useState ([]) const [query, setQuery] = useState ({}) useEffect (() => { fetch (query).then (setData) }, [query]) const opColumn = { code : 'op' , name : '操作' , width : 160 , fixed : 'right' , render : (_ : any , row : any ) => ( <Space > <Button type ="link" onClick ={() => openDetail(row)}>查看</Button > <Button type ="link" onClick ={() => edit(row)}>编辑</Button > <Popconfirm title ="删除?" onConfirm ={() => remove(row)}> <Button type ="link" danger > 删除</Button > </Popconfirm > </Space > ), } return ( <> <Filter fields ={filterFields} onQuery ={setQuery} /> <Table dataSource ={data} columns ={[...columns, opColumn ]} primaryKey ="id" rowSelection ={{ type: 'checkbox ' }} pagination ={{ pageSize: 20 , total: data.length }} scroll ={{ x: 1200 }} /> </> ) }
8.6 详情 / 审批
行”查看”→ Drawer(placement="right",宽 480)承载 DynamicForm 只读态(disabled)。
审批意见→ Modal + TextArea + Steps(当前节点高亮)+ Timeline(历史轨迹)。
状态用 Tag:type="status" + 颜色(草稿灰、审批中蓝、通过绿、驳回红)。
8.7 权限与组织
菜单:Menu 的 menuData 由后端”当前用户可访问菜单树”返回,前端只渲染有权限项。
按钮级:封装 <Auth code="po:edit"><Button>编辑</Button></Auth>,无权限则隐藏/禁用。
数据权限:列表查询自动带 deptId 等上下文。
角色分配:Transfer 左→右分配权限项。
8.8 多租户与主题
登录后取租户配置(主题色 / 品牌名 / Logo),写入 ConfigProvider 的 theme 或运行时改 CSS 变量。
提供”主题切换”面板(用 4.3 方式 C),实现换肤不刷新。
8.9 后端元数据接口约定(示例) 1 2 3 4 5 GET /meta/form/:formId → { formId, title, fields:[...] } # 渲染动态表单 POST /meta/form/:formId/submit → { ok, id } # 提交 GET /biz/:entity/list?q=... → { data:[...], total } # 列表 POST /flow/task/:taskId/complete → { ok } # 审批 GET /auth/menu → MenuNode[] # 权限菜单
8.10 工程化建议
状态:zustand(轻)或 redux-toolkit。
路由:react-router-dom v6。
请求:axios 单例 + 拦截器(401 跳登录、错误统一 Message.error)。
图表:KDesign 不含图表,报表看板接 ECharts / AntV G2 ;BI 大屏用 Card 容器包裹。
微前端:qiankun 主子应用;跨栈用 KWC 。
按需 + 主题:见第 2、4 章。
第 9 章 页面级实现(登录 / 主页 / 导航 / 菜单 / 列表 / 详情 / 系统管理)
本章给出苍穹式平台的页面级可运行实现 。技术约定:路由用 react-router-dom@6,状态用 zustand,请求用 axios。所有组件均来自 @kdcloudjs/kdesign。 关键 API 已对齐官方:Menu 用 Menu.Item / Menu.SubMenu,单选 selectedKey,onClick 返回 { key };Dropdown 用 menu 数组 + onItemClick(key);Tabs 用 Tabs.TabPane(tab/key);Card 用 title/extra/avatar。
9.1 路由与权限守卫总览 路由表(router.tsx)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import { createBrowserRouter, Navigate } from 'react-router-dom' import { AppShell } from '@/app/AppShell' import { AuthGuard } from '@/app/AuthGuard' import { Login } from '@/pages/Login' import { Dashboard } from '@/pages/Dashboard' import { PurchaseOrderList } from '@/pages/po/List' import { RoleList } from '@/pages/system/RoleList' import { NotFound } from '@/pages/NotFound' export const router = createBrowserRouter ([ { path : '/login' , element : <Login /> }, { path : '/' , element : <AuthGuard > <AppShell /> </AuthGuard > , children : [ { index : true , element : <Navigate to ="/dashboard" replace /> }, { path : 'dashboard' , element : <Dashboard /> }, { path : 'po/list' , element : <PurchaseOrderList /> }, { path : 'system/role' , element : <RoleList /> }, { path : '*' , element : <NotFound /> }, ]}, ])
鉴权守卫(AuthGuard.tsx) ——无 token 跳登录,登录后跳原页面。
1 2 3 4 5 6 7 8 9 import { Navigate , useLocation } from 'react-router-dom' import Cookies from 'js-cookie' export const AuthGuard : React .FC <{ children : React .ReactNode }> = ({ children } ) => { const token = Cookies .get ('cosmic_token' ) const location = useLocation () if (!token) return <Navigate to ="/login" state ={{ from: location.pathname }} replace /> return <> {children}</> }
全局状态(store.ts) ——页签、用户、菜单、主题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import { create } from 'zustand' interface Tab { key : string ; title : string ; path : string }interface AppState { tabs : Tab []; activeKey : string user : { name : string ; avatar ?: string } | null menuData : MenuNode [] themeColor : string openTab : (t : Tab ) => void closeTab : (key : string ) => void setActive : (key : string ) => void } export const useApp = create<AppState >((set ) => ({ tabs : [], activeKey : '' , user : null , menuData : [], themeColor : '#1f5fff' , openTab : (t ) => set (s => ({ tabs : s.tabs .find (x => x.key === t.key ) ? s.tabs : [...s.tabs , t], activeKey : t.key , })), closeTab : (key ) => set (s => ({ tabs : s.tabs .filter (x => x.key !== key) })), setActive : (key ) => set ({ activeKey : key }), }))
9.2 登录页(Login) 苍穹风登录页:左侧品牌渐变区 + 右侧表单卡片。使用 Form + Input + Switch(记住我)+ Button,校验用 async-validator,登录成功后写 Cookie 并进入工作台。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 import React , { useState } from 'react' import { Form , Input , Button , Switch , Message , Icon } from '@kdcloudjs/kdesign' import Cookies from 'js-cookie' import { useNavigate, useLocation } from 'react-router-dom' import axios from '@/services/axios' export const Login : React .FC = () => { const [form] = Form .useForm () const [loading, setLoading] = useState (false ) const [code, setCode] = useState (() => Math .random ().toString (36 ).slice (2 , 6 ).toUpperCase ()) const navigate = useNavigate () const location = useLocation () as any const onFinish = async (values : any ) => { if (values.captcha .toUpperCase () !== code) { Message .error ('验证码错误' ); setCode (rand ()); return } setLoading (true ) try { const { data } = await axios.post ('/auth/login' , { username : values.username , password : values.password }) Cookies .set ('cosmic_token' , data.token , { expires : values.remember ? 7 : 1 }) Message .success ('登录成功' ) navigate (location.state ?.from || '/dashboard' , { replace : true }) } finally { setLoading (false ) } } const rand = ( ) => Math .random ().toString (36 ).slice (2 , 6 ).toUpperCase () return ( <div style ={{ display: 'flex ', height: '100vh ', background: '#f2f2f2 ' }}> {/* 左侧品牌区 */} <div style ={{ flex: 1 , background: 'linear-gradient (135deg ,#1f5fff ,#5582f3 )', color: '#fff ', display: 'flex ', flexDirection: 'column ', justifyContent: 'center ', padding: 80 }}> <h1 style ={{ fontSize: 36 , margin: 0 }}> Cosmic 企业云</h1 > <p style ={{ opacity: .85 , marginTop: 16 , fontSize: 16 , lineHeight: 1.8 }}> 元数据驱动的低代码企业级平台<br /> 采购 · 销售 · 库存 · 财务 · 流程 · 报表,一站式协同 </p > </div > {/* 右侧表单 */} <div style ={{ width: 460 , display: 'flex ', alignItems: 'center ', justifyContent: 'center ' }}> <div style ={{ width: 320 }}> <h2 style ={{ marginBottom: 24 }}> 账号登录</h2 > <Form form ={form} layout ="vertical" onFinish ={onFinish} defaultValue ={{ remember: true }}> <Form.Item name ="username" label ="用户名" required rules ={[{ required: true , message: '请输入用户名 ' }]}> <Input placeholder ="请输入用户名" prefix ={ <Icon type ="user" /> } /> </Form.Item > <Form.Item name ="password" label ="密码" required rules ={[{ required: true , message: '请输入密码 ' }]}> <Input type ="password" placeholder ="请输入密码" prefix ={ <Icon type ="lock" /> } /> </Form.Item > <Form.Item name ="captcha" label ="验证码" required rules ={[{ required: true , message: '请输入验证码 ' }]}> <Input placeholder ="请输入右侧验证码" suffix ={ <span onClick ={() => setCode(rand())} style={{ cursor: 'pointer', letterSpacing: 2, fontWeight: 700, color: '#1f5fff' }}>{code}</span > } /> </Form.Item > <Form.Item name ="remember" > <Switch /> <span style ={{ marginLeft: 8 }}> 记住我</span > </Form.Item > <Button type ="primary" htmlType ="submit" block loading ={loading} > 登 录</Button > </Form > </div > </div > </div > ) }
要点:① Input type="password" 渲染密码框;② prefix/suffix 为可选图标槽(若版本不支持可改用 Form.Item 的 label);③ 验证码仅为前端演示,生产务必服务端校验;④ Message 为命令式轻提示。
9.3 主页 / 工作台(Dashboard) 苍穹工作台典型四块:待办统计卡 、我的待办列表 、常用功能入口 、消息时间轴 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 import React from 'react' import { Card , Row , Col , Table , Tag , Timeline , Icon , Button , Space } from '@kdcloudjs/kdesign' const stats = [ { title : '待我审批' , value : 12 , trend : '+3' , color : '#fb2323' }, { title : '我发起的' , value : 8 , trend : '+1' , color : '#1f5fff' }, { title : '本月单据' , value : 236 , trend : '+18%' , color : '#1ba854' }, { title : '逾期预警' , value : 2 , trend : '-1' , color : '#ff991c' }, ] const todos = [ { id : 1 , title : '采购订单 PO-2026-001 审批' , type : '采购' , from : '张工' , time : '2026-10-30 09:12' }, { id : 2 , title : '付款申请 AP-0098 审批' , type : '财务' , from : '李会计' , time : '2026-10-29 17:40' }, ] const todoColumns = [ { code : 'title' , name : '待办事项' , width : 320 }, { code : 'type' , name : '类型' , width : 90 , render : (v : string ) => <Tag > {v}</Tag > }, { code : 'from' , name : '发起人' , width : 100 }, { code : 'time' , name : '时间' , width : 160 }, { code : 'op' , name : '操作' , width : 100 , render : (_ : any , r : any ) => <Button type ="link" onClick ={() => alert('打开 ' + r.title)}>去处理</Button > }, ] const quick = ['新建采购订单' , '新建销售订单' , '付款申请' , '费用报销' , '库存盘点' , '基础资料' ]export const Dashboard : React .FC = () => ( <div > {/* 统计卡 */} <Row gutter ={16} > {stats.map(s => ( <Col span ={6} key ={s.title} > <Card title ={s.title} extra ={ <Icon type ="arrow-right" /> }> <div style ={{ fontSize: 30 , fontWeight: 700 , color: s.color }}> {s.value}</div > <Tag color ={s.trend.startsWith( '- ') ? 'error ' : 'success '}> 较昨日 {s.trend}</Tag > </Card > </Col > ))} </Row > {/* 待办 + 消息 */} <Row gutter ={16} style ={{ marginTop: 16 }}> <Col span ={16} > <Card title ="我的待办" extra ={ <Button type ="link" > 全部</Button > }> <Table dataSource ={todos} columns ={todoColumns} primaryKey ="id" pagination ={{ pageSize: 5 }} /> </Card > </Col > <Col span ={8} > <Card title ="消息通知" > <Timeline > <Timeline.Item color ="blue" > 系统升级维护通知(10-28)</Timeline.Item > <Timeline.Item color ="green" > 您的付款申请已通过</Timeline.Item > <Timeline.Item color ="gray" > 新同事加入采购部</Timeline.Item > </Timeline > </Card > </Col > </Row > {/* 常用功能 */} <Card title ="常用功能" style ={{ marginTop: 16 }}> <Row gutter ={[12, 12 ]}> {quick.map(q => ( <Col span ={4} key ={q} > <Card hoverable style ={{ textAlign: 'center ' }}> {q}</Card > </Col > ))} </Row > </Card > </div > )
9.4 导航布局(AppShell:顶栏 + 侧边 + 页签 + 面包屑) 苍穹标志性”顶部导航 + 可折叠左侧菜单 + 多页签工作台 + 面包屑”在此实现。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 import React , { useState } from 'react' import { Layout , Menu , Tabs , Breadcrumb , Dropdown , Button , Badge , Avatar , Icon , Switch } from '@kdcloudjs/kdesign' import { Outlet , useLocation, useNavigate } from 'react-router-dom' import { useApp } from '@/store' import { renderMenu } from './menuRender' const { Header , Sider , Content } = Layout export const AppShell : React .FC = () => { const [collapsed, setCollapsed] = useState (false ) const location = useLocation (); const navigate = useNavigate () const { tabs, activeKey, openTab, closeTab, setActive, user, menuData } = useApp () const open = (path : string , title : string ) => { openTab ({ key : path, title, path }); setActive (path); navigate (path) } const crumb = location.pathname .split ('/' ).filter (Boolean ) const userMenu = [ { label : '个人中心' , key : 'profile' }, { label : '主题设置' , key : 'theme' }, { divided : true , label : '退出登录' , key : 'logout' , danger : true }, ] return ( <Layout style ={{ height: '100vh ' }}> <Header style ={{ display: 'flex ', alignItems: 'center ', background: '#001529 ', padding: '0 16px ' }}> <div style ={{ color: '#fff ', fontWeight: 700 , fontSize: 18 , width: 200 }}> Cosmic 企业云</div > <Input placeholder ="全局搜索单据 / 客户 / 员工" style ={{ width: 280 , marginRight: 'auto ' }} prefix ={ <Icon type ="search" /> } /> <Button type ="text" icon ={ <Icon type ="skin" /> } onClick={() => navigate('/theme')} /> <Badge count ={5} > <Button type ="text" icon ={ <Icon type ="bell" /> } /></Badge > <Dropdown menu ={userMenu} trigger ="click" onItemClick ={(k: string ) => k === 'logout' && (localStorage.clear(), navigate('/login'))}> <span style ={{ color: '#fff ', cursor: 'pointer ', marginLeft: 12 }}> <Avatar src ={user?.avatar} /> {user?.name} </span > </Dropdown > </Header > <Layout > <Sider collapsible collapsed ={collapsed} onCollapse ={setCollapsed} theme ="dark" width ={220} > <Menu mode ="inline" theme ="dark" selectedKey ={location.pathname} onClick ={({ key }) => { const m = findMenu(menuData, key); open(key, m?.label || key) }}> {menuData.map(renderMenu)} </Menu > </Sider > <Content style ={{ padding: 12 , background: '#f2f2f2 ', overflow: 'auto ' }}> <Breadcrumb style ={{ marginBottom: 8 }}> <Breadcrumb.Item > 首页</Breadcrumb.Item > {crumb.map(c => <Breadcrumb.Item key ={c} > {c}</Breadcrumb.Item > )} </Breadcrumb > <Tabs type ="card" activeKey ={activeKey} onChange ={(k) => { setActive(k); navigate(k) }} onEdit={(k, a) => a === 'remove' && closeTab(k as string)}> {tabs.map(t => ( <Tabs.TabPane key ={t.key} tab ={ <span > {t.title} <Icon type ="close" style ={{ marginLeft: 8 }} onClick ={(e) => { e.stopPropagation(); closeTab(t.key) }} /> </span > } /> ))} </Tabs > <div style ={{ background: '#fff ', padding: 16 , minHeight: 400 }}> <Outlet /> </div > </Content > </Layout > </Layout > ) } function findMenu (list : any [], key : string ): any { for (const m of list) { if (m.path === key) return m if (m.children ) { const r = findMenu (m.children , key); if (r) return r } } return null }
9.5 动态菜单渲染(后端驱动) 菜单由后端”当前用户权限菜单树”返回,前端只渲染有权限项,支持多级与图标映射。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 import React from 'react' import { Menu , Icon } from '@kdcloudjs/kdesign' export interface MenuNode { key : string ; label : string ; path ?: string ; icon ?: string ; children ?: MenuNode [] } const iconMap : Record <string , string > = { dashboard : 'home' , po : 'file' , system : 'setting' , bd : 'database' , } export const renderMenu = (m : MenuNode ): React .ReactNode => { const icon = m.icon ? <Icon type ={iconMap[m.icon] || m.icon } /> : null if (m.children ?.length ) { return <Menu.SubMenu key ={m.key} title ={m.label} icon ={icon} > {m.children.map(renderMenu)} </Menu.SubMenu > } return <Menu.Item key ={m.path || m.key } icon ={icon} > {m.label}</Menu.Item > } export async function fetchMenu ( ): Promise <MenuNode []> { const res = await (await import ('@/services/axios' )).default .get ('/auth/menu' ) return res.data }
要点:① Menu.SubMenu 的标题用 title,子项用 Menu.Item;② 受控高亮用 selectedKey(单数);③ 图标通过 iconMap 把业务码映射成 kdicon 图标名;④ 权限在后端裁剪,前端无需再做隐藏逻辑。
9.6 列表 / 单据页(ProTable 实战) 以”采购订单列表”为例:工具栏(新增 / 批量删除)+ 高级筛选 Filter + Table(状态 Tag、操作列、行选择、分页)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 import React , { useState, useEffect } from 'react' import { Table , Filter , Button , Tag , Space , Popconfirm , Message } from '@kdcloudjs/kdesign' import axios from '@/services/axios' import { useNavigate } from 'react-router-dom' const statusTag : Record <string , any > = { draft : <Tag type ="status" color ="gray" > 草稿</Tag > , submitted : <Tag type ="status" color ="blue" > 审批中</Tag > , approved : <Tag type ="status" color ="green" > 已通过</Tag > , rejected : <Tag type ="status" color ="red" > 已驳回</Tag > , } const columns = [ { code : 'billNo' , name : '单据号' , width : 180 }, { code : 'supplier' , name : '供应商' , width : 160 }, { code : 'amount' , name : '金额' , width : 120 , align : 'right' }, { code : 'status' , name : '状态' , width : 100 , render : (v : string ) => statusTag[v] }, { code : 'op' , name : '操作' , width : 180 , fixed : 'right' , render : (_ : any , r : any ) => <Space > <Button type ="link" onClick ={() => openDetail(r)}>查看</Button > <Button type ="link" onClick ={() => edit(r)}>编辑</Button > <Popconfirm title ="确认删除?" onConfirm ={() => remove(r)}> <Button type ="link" danger > 删除</Button > </Popconfirm > </Space > },] const filterFields = [ { name : 'billNo' , label : '单据号' , type : 'input' }, { name : 'supplier' , label : '供应商' , type : 'input' }, { name : 'status' , label : '状态' , type : 'select' , options : [ { label : '草稿' , value : 'draft' }, { label : '审批中' , value : 'submitted' } ] }, ] export const PurchaseOrderList : React .FC = () => { const [data, setData] = useState<any []>([]) const [query, setQuery] = useState ({}) const [selected, setSelected] = useState<string []>([]) const navigate = useNavigate () const load = ( ) => axios.get ('/po/list' , { params : query }).then (r => setData (r.data .data )) useEffect (load, [query]) const openDetail = (r : any ) => navigate (`/po/detail/${r.id} ` ) const edit = (r : any ) => navigate (`/po/edit/${r.id} ` ) const remove = async (r : any ) => { await axios.delete (`/po/${r.id} ` ); Message .success ('已删除' ); load () } const batchDelete = async ( ) => { await axios.post ('/po/batch-del' , { ids : selected }); Message .success ('批量删除成功' ); load () } return ( <div > <div style ={{ marginBottom: 12 }}> <Space > <Button type ="primary" onClick ={() => navigate('/po/new')}>新增</Button > <Popconfirm title ={ `确认删除 ${selected.length } 条 ?`} onConfirm ={batchDelete} disabled ={!selected.length} > <Button danger disabled ={!selected.length} > 批量删除</Button > </Popconfirm > </Space > </div > <Filter fields ={filterFields} onQuery ={setQuery} /> <Table dataSource ={data} columns ={columns} primaryKey ="id" rowSelection ={{ type: 'checkbox ', selectedRowKeys: selected , onChange: (keys: any ) => setSelected(keys) }} pagination={{ pageSize: 20, total: data.length }} scroll={{ x: 1000 }} /> </div > ) }
9.7 详情 / 表单页(抽屉 + 编辑) 行”查看”→右侧 Drawer 承载只读表单(复用第 8.4 节 DynamicForm,disabled);”编辑/新增”→整页表单。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import React , { useEffect, useState } from 'react' import { Drawer , Button , Descriptions , Spin } from '@kdcloudjs/kdesign' import axios from '@/services/axios' export const OrderDetailDrawer : React .FC <{ id : string ; visible : boolean ; onClose : () => void }> = ({ id, visible, onClose } ) => { const [detail, setDetail] = useState<any >(null ) useEffect (() => { if (visible && id) axios.get (`/po/${id} ` ).then (r => setDetail (r.data )) }, [visible, id]) return ( <Drawer title ="采购订单详情" visible ={visible} width ={520} onClose ={onClose} footer ={ <Button onClick ={onClose} > 关闭</Button > }> {!detail ? <Spin spinning /> : ( <Descriptions column ={1} title ="基本信息" > <Descriptions.Item label ="单据号" > {detail.billNo}</Descriptions.Item > <Descriptions.Item label ="供应商" > {detail.supplier}</Descriptions.Item > <Descriptions.Item label ="金额" > {detail.amount}</Descriptions.Item > <Descriptions.Item label ="状态" > {detail.status}</Descriptions.Item > </Descriptions > )} </Drawer > ) }
进阶:把详情里每个字段也用第 8.4 节的 DynamicForm(schema, { initial: detail, disabled: true }) 渲染,即可做到”元数据驱动详情页”,无需为每张单据写死页面。
9.8 系统管理(用户 / 角色 / 权限) 角色管理 :角色表格 + 抽屉用 Transfer 分配菜单/权限项(苍穹式权限分配)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 import React , { useState } from 'react' import { Table , Button , Drawer , Transfer , Tag , Modal , Message } from '@kdcloudjs/kdesign' import axios from '@/services/axios' const roleColumns = [ { code : 'name' , name : '角色名' , width : 160 }, { code : 'desc' , name : '说明' , width : 240 }, { code : 'count' , name : '成员数' , width : 100 }, { code : 'op' , name : '操作' , width : 160 , render : (_ : any , r : any ) => <Button type ="link" onClick ={() => openAuth(r)}>权限分配</Button > }, ] export const RoleList : React .FC = () => { const [roles, setRoles] = useState<any []>([]) const [cur, setCur] = useState<any >(null ) const [targetKeys, setTargetKeys] = useState<string []>([]) const [perms, setPerms] = useState<any []>([]) const openAuth = async (r : any ) => { setCur (r) const [p, owned] = await Promise .all ([axios.get ('/auth/perms' ), axios.get (`/auth/role/${r.id} /perms` )]) setPerms (p.data ); setTargetKeys (owned.data ); setCur (r) } const save = async ( ) => { await axios.post (`/auth/role/${cur.id} /perms` , { keys : targetKeys }); Message .success ('已保存' ); setCur (null ) } return ( <> <Table dataSource ={roles} columns ={roleColumns} primaryKey ="id" /> <Drawer title ={ `权限分配 · ${cur ?.name }`} visible ={!!cur} width ={560} onClose ={() => setCur(null)} footer={<> <Button onClick ={() => setCur(null)}>取消</Button > <Button type ="primary" onClick ={save} > 保存</Button > </> }> <Transfer dataSource ={perms} targetKeys ={targetKeys} titles ={[ '可选权限 ', '已授权 ']} showSearch onChange ={(keys: any ) => setTargetKeys(keys)} /> </Drawer > </> ) }
用户管理页同理:Table 列出用户,Drawer 内用 Form 编辑(账号/姓名/部门/角色多选 Select mode="multiple")。权限粒度做到”菜单 + 按钮”,前端用第 8.7 节的 <Auth code="po:edit"> 控制按钮显隐。
9.9 个人中心 / 设置 用 Tabs 组织”基本资料 / 修改密码 / 主题设置”三块,Card 承载表单,Switch 切换主题色(写回 ConfigProvider 或 CSS 变量)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 import React from 'react' import { Tabs , Card , Form , Input , Button , Switch , Avatar , Message } from '@kdcloudjs/kdesign' import { useApp } from '@/store' export const Profile : React .FC = () => { const { themeColor, setTheme } = useApp () return ( <Card > <Tabs type ="line" > <Tabs.TabPane key ="base" tab ="基本资料" > <Form layout ="vertical" style ={{ maxWidth: 420 }}> <Form.Item name ="name" label ="姓名" > <Input /> </Form.Item > <Form.Item name ="dept" label ="部门" > <Input /> </Form.Item > <Form.Item name ="email" label ="邮箱" > <Input /> </Form.Item > <Button type ="primary" onClick ={() => Message.success('已保存')}>保存</Button > </Form > </Tabs.TabPane > <Tabs.TabPane key ="pwd" tab ="修改密码" > <Form layout ="vertical" style ={{ maxWidth: 420 }}> <Form.Item name ="old" label ="原密码" required > <Input type ="password" /> </Form.Item > <Form.Item name ="next" label ="新密码" required > <Input type ="password" /> </Form.Item > <Button type ="primary" > 提交</Button > </Form > </Tabs.TabPane > <Tabs.TabPane key ="theme" tab ="主题设置" > <p > 科技蓝 <Switch checked ={themeColor === '#1f5fff' } onChange ={v => setTheme(v ? '#1f5fff' : '#5582f3')} /></p > <Avatar style ={{ background: themeColor }}> C</Avatar > </Tabs.TabPane > </Tabs > </Card > ) }
9.10 页面级最佳实践
页签保活(keep-alive) :KDesign 无内置 keep-alive。简单方案渲染所有已开页签、非激活者 display:none;要严格保活可引入 react-activation 的 <AliveScope> + <KeepAlive> 包裹 Outlet。
路由懒加载 :const Dashboard = lazy(() => import('@/pages/Dashboard')),配合 <Suspense fallback={<Spin spinning />}> 提升首屏。
全局 Loading :axios 拦截器统一开关 Spin(可用 message 或顶部 Progress)。
错误与权限页 :NotFound(404)、Forbidden(403 无权限)独立页面;用 ErrorBoundary 兜底渲染异常。
面包屑自动生成 :基于 useLocation() + 菜单树(见 9.4 findMenu)自动拼面包屑,无需每页手写。
表单/列表二次封装 :把 9.2–9.8 的重复模式沉淀为 ProForm / ProTable / PageHeader / Auth 业务组件(第 10 章继续展开),保证全站交互一致。
响应式 :Sider 设 breakpoint="lg" 在窄屏自动收起;Row/Col 栅格适配;移动端用 KWC 或独立 H5。
第 10 章 工程实践与最佳实践 9.1 推荐目录结构 1 2 3 4 5 6 7 8 9 src/ ├─ app/ AppShell, router, store, ConfigProvider ├─ components/ ProForm, ProTable, Auth, PageHeader(二开封装) ├─ form-engine/ schema 类型, widgetRegistry, DynamicForm ├─ pages/ 业务页面(按模块) ├─ services/ api 请求层 ├─ theme/ cosmic-theme.less, tokens.ts ├─ locales/ 语言包 └─ utils/
9.2 二次封装(Pro 思路) 把高频组合封装成业务组件(ProForm / ProTable / PageHeader / Auth),统一苍穹交互,避免每页重复。参考 Antd ProComponents 思路,但全部基于 KDesign。
9.3 设计令牌与品牌 集中管理 tokens.ts(映射 Less 变量),切换租户时改 CSS 变量;保持 borderType 全局一致。
9.4 可访问性 / 全键盘 苍穹类密集录单场景,依赖 KDesign 全键盘。表单用 Form.Item 合理排序,required 明确必录样式。
9.5 测试 KDesign 自带 Jest 测试体系;业务侧用 @testing-library/react + jest 测渲染器与组件。
9.6 版本与升级
锁定 @kdcloudjs/kdesign 次版本,升级看 changelog 。
注意 Table 的 code 字段键、Form 的 async-validator 规则在升级间的兼容性。
第 11 章 常见问题 FAQ Q1:React 18 能用吗? peerDependencies 为 react >=16.9.0。16/17 完全稳定;18 用 createRoot 一般可用(styled-components@5 兼容 18),但请自测浮层与 findDOMNode 相关警告。
Q2:主题不生效? less-loader 必须处理 node_modules/@kdcloudjs/kdesign 的 less;用 modifyVars 且 javascriptEnabled: true;变量名用文档给定的(@theme-color / theme-color)。
Q3:表格不显示数据? 列用 code 不是 dataIndex;开启行选择必须设 primaryKey;给 Table 明确宽高(或父容器有高度),否则自适应异常。
Q4:IE11 白屏? 已内置 css-vars-ponyfill / @babel/polyfill;确保打包未排除 KDesign 的 polyfill,构建目标含 ie >= 11。
Q5:多套 UI 库类名冲突? 用 ConfigProvider 的 prefixCls 给 KDesign 加前缀隔离;跨栈用 KWC。
Q6:KDesign 有图表 / 流程设计器吗? 没有。图表用 ECharts/AntV;流程设计器需自研或集成 BPMN.js,KDesign 提供 Steps/Timeline/Modal 等展示与交互原子。
Q7:动态表单一定要 Formily 吗? 不一定。KDesign 自带 Form 足够简单表单;低代码/元数据驱动表单用第 8.4 节的”Schema + 自研渲染器”即可,无需引入 Formily(Formily 默认绑定 antd,接 KDesign 需自定义桥接,成本更高)。
附录 A. 全量组件速查(按官网分类)
基础 :Button、Clipboard、Icon、Link、Pagination、QRCode、SVGIcon、Typography
布局 :Divider、Grid(Row/Col)、Layout(Header/Sider/Content/Footer)、Space、SplitPanel
导航 :Anchor、Breadcrumb、Dropdown、Menu、Steps、Tabs、Tree
表单 :BaseData、Cascader、Checkbox、CityPicker、ColorPicker、DatePicker、Form、GeoZonePicker、ImageCropper、Input、InputNumber、Radio、Rate、Select、Signature、Slider、Stepper、Switch、Transfer、TreeSelect、Upload
展示 :Avatar、Badge、Card、Carousel、Collapse、Drawer、Image、SplitPanel、Table、Tag、Timeline
反馈 :Alert、Empty、Message、Modal、Notification、Popconfirm、Progress、Spin、Tooltip
筛选 :Filter、Search
B. 设计令牌速记(换肤必改) @theme-color(主题色)、@success/warning/error/ongoing-color(语义色)、@primary/secondary/third-text-color(文本)、@radius-size(圆角)、@strong/weak-border-color(边框)、@bg/@bg2/@contain-bg(背景)。
C. 参考链接
手册结束。按第 2 章起步,第 8 章组装,即可在 KDesign 之上构建出”类金蝶云苍穹”的企业级中后台 / 低代码平台。