行业知识
【React】AntV G6 - 快速入手
2026-11-26 09:19:34
来源:互联网转载
环境
- react: ^18
- next: 14.1.0
- @antv/g6: ^4.8.24
安装
npm install @antv/g6# orpnpm 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(null); const graphRef = React.useRef(); 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 containerRef};}export default ForceGraph组件调用
// file: app/pages.tsximport 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 ( data.nodes}edges={data.edges}/ )}效果
上一篇:云端云服务器怎么购买?