mcpField
R
react-flow-usage

react-flow-usage

github.com/thedogwiththedataonit开发637 次安装40 周前更新
代码仓库

关于 react-flow-usage

react-flow-usage 是使用 React Flow(@xyflow/react v12+)构建节点界面的技能指南,涵盖组件模式、状态、性能、布局和交互,适用于工作流编辑器与流程图。

主要功能

  1. 01自定义节点与边模式
  2. 02流程状态与 Hooks
  3. 03拖放交互
  4. 04保存和恢复流程
  5. 05布局与性能指导

适用场景

  1. 01构建工作流编辑器
  2. 02创建自定义节点界面
  3. 03实现流程保存与恢复
  4. 04优化大型图的性能

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/thedogwiththedataonit/react-flow --skill react-flow-usage

安装后在 Claude Code 中输入/react-flow-usage确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

.gitignore
AGENTS.md
ALL_LINKS.md
README.md
metadata.json
rules/
interaction-drag-drop.md
_sections.md
hook-use-nodes-data.md
_template.md
edge-connection-validation.md
layout-auto-dagre.md
node-custom-handles.md
setup-nodetypes-outside.md
setup-imports-css.md
perf-memo-custom-components.md
state-save-restore.md
typescript-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-
6Hook 用法中hook-
7布局与定位中layout-
8交互模式中interaction-
9TypeScript 集成中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 ID
  • type:'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/

常见问题

  1. 无法创建边 - 添加 onConnect 处理函数
  2. 节点无法拖动 - 检查 nodesDraggable 属性
  3. CSS 未加载 - 导入 @xyflow/react/dist/style.css
  4. 在提供程序外使用 useReactFlow - 使用 <ReactFlowProvider> 包裹
  5. 性能问题 - 查看性能类别规则
  6. TypeScript 错误 - 使用正确的泛型类型 useReactFlow<NodeType, EdgeType>()

参考资料

评论

支持 Markdown