本文主要是介绍【React】AntV G6 - 快速入手,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
环境
- react:
^18
- next:
14.1.0
- @antv/g6:
^4.8.24
安装
npm install @antv/g6# or
pnpm add @antv/g6# or
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组件
// file: component/ForceGraph/index.tsx
"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.nodesif (props.edges)data.edges=props.edgesconst _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
组件调用
// file: app/pages.tsx
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><ForceGraphnodes={data.nodes}edges={data.edges}/></div>)
}
效果
这篇关于【React】AntV G6 - 快速入手的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!