环境
- react:
^18
- next:
14.1.0
- @antv/g6:
^4.8.24
安装
npm install @antv/g6
pnpm add @antv/g6
yarn add @antv/g6
使用
模拟数据
const data = {
nodes: [
{
id: "node1",
data: {
name: "Circle1"
}
},
{
id: "node2",
data: {
name: "Circle2"
}
}
],
edges: [
{
id: "edge1",
source: "node1",
target: "node2"
}
]
};
示例
创建ForceGraph组件
"use client"
import type { GraphOptions, GraphData } from '@antv/g6';
import React, {useEffect, useRef} from "react"
import { Graph } from '@antv/g6';
interface Props{
nodes: any[],
edges: any[],
options?: GraphOptions
}
const defaultOptions = {
width: 500,
height: 500,
defaultNode: {
type: "circle",
size: [100],
color: "#5B8FF9",
style: {
fill: "#9EC9FF",
lineWidth: 3
},
labelCfg: {
style: {
fill: "#fff",
fontSize: 20
}
}
},
defaultEdge: {
style: {
stroke: "#e2e2e2"
}
}
};
const ForceGraph = function (
props:Props
) {
const containerRef= useRef<HTMLDivElement | null>(null);
const graphRef = React.useRef<Graph>();
const data:GraphData = {nodes:[], edges:[]};
useEffect(()=>{
if(graphRef.current || !containerRef.current)return;
if (props.nodes)data.nodes=props.nodes
if (props.edges)data.edges=props.edges
const _options = Object.assign({}, defaultOptions, props.options);
_options.container = containerRef.current;
const graph = new Graph(_options);
graph.data(data);
graph.render();
graphRef.current = graph;
},
[
props.nodes,
props.edges,
])
return <div ref={containerRef}></div>;
}
export default ForceGraph
组件调用
import ForceGraph from "@/component/ForceGraph";
export default function Home(){
const data = {
nodes: [
{ id: 'node1', data: { name: 'Circle1' } },
{ id: 'node2', data: { name: 'Circle2' } },
],
edges: [{ id: 'edge1', source: 'node1', target: 'node2', data: {} }],
};
return (
<div>
<ForceGraph
nodes={data.nodes}
edges={data.edges}
/>
</div>
)
}
效果