1.首先我们需要下载相关的依赖
npm install --save @antv/g6
2.页面组件中引入G6依赖
import G6 from '@antv/g6';
3.官网选择合适示例:复制核心代码块,dom容器的id值要和核心代码块中的容器属性值一致。
注: 因为初始化graph需要等dom渲染之后,否则找不到container对应div容器。 核心代码块需要放置在created之后的生命函数里, 而不是直接在组件created阶段。
完整代码:
import React, { useEffect } from 'react';
import G6 from '@antv/g6';
import Hierarchy from '@antv/hierarchy';
import style from './style.less';
export const index = () => {
useEffect(() => {
var r = 50;
var radius = Math.PI;
var graph = new G6.Graph({
container: 'mountNode',
width: window.innerWidth,
height: window.innerHeight,
animate: true,
animateCfg: {
duration: 1000,
onFrame: function onFrame(node, ratio, toAttrs: any, fromAttrs: any) {
var current = radius * ratio;
var x = fromAttrs.x;
var y = fromAttrs.y;
if (fromAttrs.x > toAttrs.x) {
x = x - r + r * Math.cos(current);
y += r * Math.sin(current);
} else {
x = x + r - r * Math.cos(current);
y -= r * Math.sin(current);
}
return {
x: x,
y: y,
};
},
},
});
var node1 = graph.addItem('node', {
id: 'node1',
x: 500,
y: 300,
shape: 'circle',
style: {
fill: '#F04864',
lineWidth: 2,
},
});
var node2 = graph.addItem('node', {
id: 'node2',
x: 400,
y: 300,
shape: 'circle',
style: {
fill: '#40a9ff',
lineWidth: 0,
},
});
var count = 0;
setInterval(function() {
var model = node1.get('model');
if (count % 2 === 0) {
node1.get('model').x = 200;
node2.get('model').x = 100;
} else {
node1.get('model').x = 100;
node2.get('model').x = 200;
}
count++;
graph.refresh();
}, 1000);
}, []);
return <div id={'mountNode'} className={style.mountNode}></div>;
};
export default index;
页面效果: