求完整可用的React-Sigma力导向布局实现示例
React + SigmaJS 力导向布局完整可运行示例
不用放弃react-sigma,下面是一个单文件、完整可用的力导向布局实现,基于@react-sigma/core和ForceAtlas2布局:
第一步:安装依赖
npm install @react-sigma/core sigma graphology graphology-layout-forceatlas2
完整组件代码
import React, { useEffect, useRef } from 'react'; import { Sigma, Graph, Controls } from '@react-sigma/core'; import ForceAtlas2 from 'graphology-layout-forceatlas2'; import '@react-sigma/core/lib/react-sigma.css'; const ForceLayoutExample = () => { const graphRef = useRef(null); // 示例图数据(可替换为你的业务数据) const graphData = { nodes: [ { id: 'n1', label: 'Node 1', x: 0, y: 0, size: 10 }, { id: 'n2', label: 'Node 2', x: 10, y: 10, size: 8 }, { id: 'n3', label: 'Node 3', x: -10, y: 10, size: 8 }, { id: 'n4', label: 'Node 4', x: 0, y: -10, size: 8 }, { id: 'n5', label: 'Node 5', x: 20, y: 0, size: 6 }, ], edges: [ { id: 'e1', source: 'n1', target: 'n2' }, { id: 'e2', source: 'n1', target: 'n3' }, { id: 'e3', source: 'n1', target: 'n4' }, { id: 'e4', source: 'n2', target: 'n5' }, ], }; useEffect(() => { if (!graphRef.current) return; const graph = graphRef.current; // 初始化ForceAtlas2布局,参数可按需调整 const layout = ForceAtlas2.instantiate(graph, { adjustSizes: true, edgeWeightInfluence: 1, scalingRatio: 2, strongGravityMode: true, // 防止节点过度分散 gravity: 1, }); // 启动布局动画循环 let animationFrameId; const animate = () => { layout.tick(); // 执行一次布局计算 graph.refresh(); // 通知Sigma重绘图 animationFrameId = requestAnimationFrame(animate); }; animate(); // 组件卸载时清理资源 return () => { layout.stop(); cancelAnimationFrame(animationFrameId); }; }, []); return ( <div style={{ height: '600px', width: '100%' }}> <Sigma settings={{ enableWebGL: true, minCameraRatio: 0.1 }}> <Graph ref={graphRef} data={graphData} /> <Controls /> {/* 提供缩放、拖拽等交互控件 */} </Sigma> </div> ); }; export default ForceLayoutExample;
关键细节说明
布局动画生效的核心:
- 通过
requestAnimationFrame创建循环,每次调用layout.tick()更新节点位置 - 必须调用
graph.refresh()触发Sigma的重绘,否则节点位置不会更新
- 通过
布局参数调整:
strongGravityMode:开启后节点会被拉向中心,避免飞散gravity:控制中心引力大小,数值越大节点越集中scalingRatio:控制节点间的排斥力,数值越大节点间距越大
React生命周期适配:
- 用
useRef获取Graph实例,避免每次渲染重新创建布局 - 在
useEffect中初始化布局和动画,组件卸载时清理布局和动画帧,防止内存泄漏
- 用
渲染性能优化:
- 启用
enableWebGL: true利用GPU加速渲染,适合节点较多的场景 - 给容器设置固定高度,Sigma需要明确的渲染区域尺寸
- 启用
常见问题排查
- 布局无动画:检查是否调用了
layout.tick()和graph.refresh(),确认布局实例已正确绑定到Graph - 节点飞散:增大
gravity值或开启strongGravityMode - 渲染卡顿:减少节点数量、简化节点样式,或确保启用WebGL
内容的提问来源于stack exchange,提问作者dcsan
相关产品推荐
相关产品推荐

