低代码可视化搭建
概述
低代码可视化搭建平台允许用户通过拖拽、配置面板等交互方式搭建数据大屏和图表页面,无需编写代码。核心技术包括 Schema 驱动渲染、拖拽引擎和属性配置面板。
架构设计
核心模块
Schema 定义
// 页面 Schema
interface PageSchema {
id: string;
name: string;
width: number;
height: number;
backgroundColor: string;
components: ComponentSchema[];
}
// 组件 Schema
interface ComponentSchema {
id: string;
type: string; // 组件类型:'bar-chart' | 'line-chart' | 'text' | ...
props: Record<string, unknown>; // 组件属性(数据源、样式等)
position: { x: number; y: number };
size: { width: number; height: number };
zIndex: number;
dataSource?: DataSourceConfig;
}
// 数据源配置
interface DataSourceConfig {
type: 'static' | 'api' | 'websocket';
config: {
url?: string;
method?: string;
interval?: number; // 轮询间隔
staticData?: unknown; // 静态数据
};
}
渲染引擎
import { useMemo } from 'react';
// 组件注册表
const componentRegistry = new Map<string, React.ComponentType<Record<string, unknown>>>();
function registerComponent(type: string, component: React.ComponentType<Record<string, unknown>>): void {
componentRegistry.set(type, component);
}
// 渲染引擎:根据 Schema 渲染组件
function SchemaRenderer({ schema }: { schema: PageSchema }) {
return (
<div
style={{
width: schema.width,
height: schema.height,
backgroundColor: schema.backgroundColor,
position: 'relative',
}}
>
{schema.components.map((comp) => {
const Component = componentRegistry.get(comp.type);
if (!Component) return null;
return (
<div
key={comp.id}
style={{
position: 'absolute',
left: comp.position.x,
top: comp.position.y,
width: comp.size.width,
height: comp.size.height,
zIndex: comp.zIndex,
}}
>
<Component {...comp.props} />
</div>
);
})}
</div>
);
}
属性配置面板
// 组件属性 Schema(用于生成配置面板)
interface PropFieldSchema {
key: string;
label: string;
type: 'input' | 'number' | 'color' | 'select' | 'switch' | 'json';
defaultValue?: unknown;
options?: { label: string; value: string }[];
}
// 每个图表组件声明自己的可配置属性
const barChartPropSchema: PropFieldSchema[] = [
{ key: 'title', label: '标题', type: 'input', defaultValue: '柱状图' },
{ key: 'color', label: '颜色', type: 'color', defaultValue: '#5470c6' },
{ key: 'showLabel', label: '显示标签', type: 'switch', defaultValue: false },
{
key: 'direction',
label: '方向',
type: 'select',
defaultValue: 'vertical',
options: [
{ label: '垂直', value: 'vertical' },
{ label: '水平', value: 'horizontal' },
],
},
];
拖拽交互
拖拽引擎通常基于 HTML5 Drag and Drop API 或 Pointer Events 实现,详见 拖拽排序。
核心功能:
- 从物料库拖入画布
- 画布内移动、缩放组件
- 对齐辅助线(磁吸吸附)
- 多选和组合
- 撤销/重做(Command 模式)
常见面试问题
Q1: 低代码可视化搭建的核心技术是什么?
答案:
- Schema 驱动:用 JSON 描述页面结构和组件配置
- 拖拽引擎:Pointer Events 实现拖放、缩放、对齐
- 组件注册表:动态注册和渲染不同图表类型
- 属性面板:根据组件 Schema 动态生成配置表单
- 渲染引擎:将 Schema 解析为实际组件树
Q2: 如何设计可视化搭建平台的 Schema?
答案:
页面 Schema 包含全局配置(尺寸、背景)和组件数组。每个组件 Schema 包含:type(组件类型)、props(属性配置)、position/size(位置尺寸)、dataSource(数据源配置)。Schema 需要支持序列化存储和版本管理。
Q3: 如何实现撤销/重做功能?
答案:
使用命令模式(Command Pattern):每个操作(移动、修改属性、删除等)封装为 Command 对象(包含 execute 和 undo 方法),维护 undo/redo 两个栈。执行操作时压入 undo 栈,撤销时弹出执行 undo 并压入 redo 栈。详见 命令模式。