在 React 中使用
阅读时间约 2 分钟
参考下面的示例,你可以在 React 中使用 G6,也可以查看 在线示例 。
import { Graph } from '@antv/g6';import { useEffect, useRef } from 'react';export default () => {const containerRef = useRef<HTMLDivElement>(null);useEffect(() => {const graph = new Graph({container: containerRef.current!,width: 500,height: 500,data: {nodes: [{id: 'node-1',style: { x: 50, y: 100 },},{id: 'node-2',style: { x: 150, y: 100 },},],edges: [{ id: 'edge-1', source: 'node-1', target: 'node-2' }],},});graph.render();}, []);return <div ref={containerRef} />;};
在严格模式下,React 会二次更新导致 G6 重复创建 Graph 实例并销毁,可以参考如下示例解决:
import type { GraphOptions } from '@antv/g6';import { Graph as G6Graph } from '@antv/g6';import { useEffect, useRef } from 'react';export interface GraphProps {options: GraphOptions;onRender?: (graph: G6Graph) => void;onDestroy?: () => void;}export const Graph = (props: GraphProps) => {const { options, onRender, onDestroy } = props;const graphRef = useRef<G6Graph>();const containerRef = useRef<HTMLDivElement>(null);useEffect(() => {const graph = new G6Graph({ container: containerRef.current! });graphRef.current = graph;return () => {const graph = graphRef.current;if (graph) {graph.destroy();onDestroy?.();graphRef.current = undefined;}};}, []);useEffect(() => {const container = containerRef.current;const graph = graphRef.current;if (!options || !container || !graph || graph.destroyed) return;graph.setOptions(options);graph.render().then(() => onRender?.(graph))// eslint-disable-next-line no-console.catch((error) => console.debug(error));}, [options]);return <div ref={containerRef} style={{ width: '100%', height: '100%' }} />;};