关于 react-flow-usage
react-flow-usage 是使用 React Flow(@xyflow/react v12+)构建节点界面的技能指南,涵盖组件模式、状态、性能、布局和交互,适用于工作流编辑器与流程图。
主要功能
- 01自定义节点与边模式
- 02流程状态与 Hooks
- 03拖放交互
- 04保存和恢复流程
- 05布局与性能指导
适用场景
- 01构建工作流编辑器
- 02创建自定义节点界面
- 03实现流程保存与恢复
- 04优化大型图的性能
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ thedogwiththedataonit/ react-flow --skill react-flow-usage安装后在 Claude Code 中输入/react-flow-usage确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
.gitignoreAGENTS.mdALL_LINKS.mdREADME.mdmetadata.jsonrules/interaction-drag-drop.md_sections.mdhook-use-nodes-data.md_template.mdedge-connection-validation.mdlayout-auto-dagre.mdnode-custom-handles.mdsetup-nodetypes-outside.mdsetup-imports-css.mdperf-memo-custom-components.mdstate-save-restore.mdtypescript-typed-nodes-edges.md详细介绍
React Flow 使用指南
使用 React Flow(@xyflow/react v12+)构建适用于生产环境的基于节点的 UI 的全面模式和最佳实践。
何时使用此技能
在以下情况下应用这些指南:
- 构建工作流编辑器、流程图或基于节点的界面
- 创建自定义节点或边组件
- 为可视化编程实现拖放功能
- 优化包含 100+ 个节点的图的性能
- 管理流程状态、保存/恢复或撤销/重做
- 使用 dagre、elkjs 或自定义算法实现自动布局
- 将 React Flow 与 TypeScript 集成
按优先级划分的规则类别
| 优先级 | 类别 | 重点 | 前缀 |
|---|---|---|---|
| 1 | 设置与配置 | 关键 | setup- |
| 2 | 性能优化 | 关键 | perf- |
| 3 | 节点模式 | 高 | node- |
| 4 | 边模式 | 高 | edge- |
| 5 | 状态管理 | 高 | state- |
| 6 | Hook 用法 | 中 | hook- |
| 7 | 布局与定位 | 中 | layout- |
| 8 | 交互模式 | 中 | interaction- |
| 9 | TypeScript 集成 | 中 | typescript- |
快速入门模式
import { useCallback } from 'react';
import {
ReactFlow,
Background,
Controls,
MiniMap,
useNodesState,
useEdgesState,
addEdge
} from '@xyflow/react';
import '@xyflow/react/dist/style.css';
const initialNodes = [
{ id: '1', position: { x: 0, y: 0 }, data: { label: 'Node 1' } },
];
const initialEdges = [
{ id: 'e1-2', source: '1', target: '2' },
];
// Define outside component or use useMemo
const nodeTypes = { custom: CustomNode };
const edgeTypes = { custom: CustomEdge };
function Flow() {
const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
const onConnect = useCallback(
(params) => setEdges((eds) => addEdge(params, eds)),
[setEdges]
);
return (
<div style={{ width: '100%', height: '100vh' }}>
<ReactFlow
nodes={nodes}
edges={edges}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
nodeTypes={nodeTypes}
edgeTypes={edgeTypes}
fitView
>
<Background />
<Controls />
<MiniMap />
</ReactFlow>
</div>
);
}
核心概念概览
节点结构
id:唯一标识符(必填)position:{ x: number, y: number }(必填)data:自定义数据对象(必填)type:内置或自定义类型style、className:样式draggable、selectable、connectable:交互控制parentId:用于嵌套/分组节点extent:移动边界
边结构
id:唯一标识符(必填)source:源节点 ID(必填)target:目标节点 ID(必填)sourceHandle、targetHandle:特定的 handle IDtype:'default' | 'straight' | 'step' | 'smoothstep' | 自定义animated:是否启用动画label:字符串或 React 组件markerStart、markerEnd:箭头标记
Handle 用法
- 位置:
Position.Top | Bottom | Left | Right - 类型:
'source' | 'target' - 支持每个节点有多个 handle
- 多个 handle 时使用唯一的
id属性
基本模式
自定义节点
import { memo } from 'react';
import { Handle, Position, NodeProps } from '@xyflow/react';
const CustomNode = memo(({ data, selected }: NodeProps) => {
return (
<div className={`custom-node ${selected ? 'selected' : ''}`}>
<Handle type="target" position={Position.Top} />
<div>{data.label}</div>
<Handle type="source" position={Position.Bottom} />
</div>
);
});
// IMPORTANT: Define outside component
const nodeTypes = { custom: CustomNode };
自定义边
import { BaseEdge, EdgeLabelRenderer, getBezierPath, EdgeProps } from '@xyflow/react';
function CustomEdge({ id, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition }: EdgeProps) {
const [edgePath, labelX, labelY] = getBezierPath({
sourceX, sourceY, sourcePosition, targetX, targetY, targetPosition,
});
return (
<>
<BaseEdge path={edgePath} />
<EdgeLabelRenderer>
<div style={{
position: 'absolute',
transform: `translate(-50%, -50%) translate(${labelX}px,${labelY}px)`,
}}>
Custom Label
</div>
</EdgeLabelRenderer>
</>
);
}
性能优化
// 1. Memoize node/edge types (define outside component)
const nodeTypes = useMemo(() => ({ custom: CustomNode }), []);
// 2. Memoize callbacks
const onConnect = useCallback((params) =>
setEdges((eds) => addEdge(params, eds)), [setEdges]
);
// 3. Use simple edge types for large graphs
const edgeType = nodes.length > 100 ? 'straight' : 'smoothstep';
// 4. Avoid unnecessary re-renders in custom components
const CustomNode = memo(({ data }) => <div>{data.label}</div>);
关键 Hook
useReactFlow()- 访问流程实例方法(getNodes、setNodes、fitView 等)useNodesState()/useEdgesState()- 带变更处理器的托管状态useNodes()/useEdges()- 响应式访问当前节点/边useNodesData(id)- 获取特定节点数据(比 useNodes 性能更好)useHandleConnections()- 获取某个 handle 的连接useConnection()- 跟踪正在进行的连接useStore()- 直接访问 store(谨慎使用)
常见模式
拖放
const onDrop = useCallback((event) => {
event.preventDefault();
const type = event.dataTransfer.getData('application/reactflow');
const position = screenToFlowPosition({
x: event.clientX,
y: event.clientY,
});
setNodes((nds) => nds.concat({
id: getId(),
type,
position,
data: { label: `${type} node` },
}));
}, [screenToFlowPosition]);
保存与恢复
const { toObject } = useReactFlow();
// Save
const flow = toObject();
localStorage.setItem('flow', JSON.stringify(flow));
// Restore
const flow = JSON.parse(localStorage.getItem('flow'));
setNodes(flow.nodes || []);
setEdges(flow.edges || []);
setViewport(flow.viewport);
连接验证
const isValidConnection = useCallback((connection) => {
// Prevent self-connections
if (connection.source === connection.target) return false;
// Custom validation logic
return true;
}, []);
详细规则
如需查看全面的模式和最佳实践,请参阅 rules/ 目录中按类别整理的各个规则文件:
rules/setup-*.md - Critical setup patterns
rules/perf-*.md - Performance optimization
rules/node-*.md - Node customization patterns
rules/edge-*.md - Edge handling patterns
rules/state-*.md - State management
rules/hook-*.md - Hooks usage
rules/layout-*.md - Layout and positioning
rules/interaction-*.md - User interactions
rules/typescript-*.md - TypeScript integration
完整汇编文档
如需查看包含所有规则和展开示例的完整指南,请参阅 AGENTS.md
抓取的文档参考
reactflow.dev 的完整抓取文档位于 scraped/:
- 学习:
scraped/learn-concepts/、scraped/learn-customization/、scraped/learn-advanced/ - API:
scraped/api-hooks/、scraped/api-types/、scraped/api-utils/、scraped/api-components/ - 示例:
scraped/examples-nodes/、scraped/examples-edges/、scraped/examples-interaction/、scraped/examples-layout/ - UI 组件:
scraped/ui-components/ - 教程:
scraped/learn-tutorials/ - 故障排查:
scraped/learn-troubleshooting/
常见问题
- 无法创建边 - 添加
onConnect处理函数 - 节点无法拖动 - 检查
nodesDraggable属性 - CSS 未加载 - 导入
@xyflow/react/dist/style.css - 在提供程序外使用 useReactFlow - 使用
<ReactFlowProvider>包裹 - 性能问题 - 查看性能类别规则
- TypeScript 错误 - 使用正确的泛型类型
useReactFlow<NodeType, EdgeType>()
参考资料
- 官方文档:https://reactflow.dev
- GitHub:https://github.com/xyflow/xyflow
- 软件包:
@xyflow/react(npm) - 示例:https://reactflow.dev/examples
- API 参考:https://reactflow.dev/api-reference
评论
支持 Markdown