1- import React from 'react'
1+ import React , { useEffect , useRef } from 'react'
22import { Graph , Keyboard , Selection } from '@antv/x6'
33import '../../index.less'
44
5- export class SelectionExample extends React . Component {
6- private container ! : HTMLDivElement
5+ export const SelectionExample : React . FC = ( ) => {
6+ const containerRef = useRef < HTMLDivElement > ( null )
7+ const graphRef = useRef < Graph | null > ( null )
8+
9+ useEffect ( ( ) => {
10+ if ( ! containerRef . current ) return
711
8- componentDidMount ( ) {
912 const graph = new Graph ( {
10- container : this . container ,
13+ container : containerRef . current ,
1114 width : 1200 ,
1215 height : 800 ,
1316 grid : true ,
@@ -27,6 +30,8 @@ export class SelectionExample extends React.Component {
2730 graph . use ( keyboard )
2831 graph . use ( selection )
2932
33+ graphRef . current = graph
34+
3035 // 生成500个节点
3136 const nodes = [ ]
3237 const nodeWidth = 80
@@ -139,17 +144,16 @@ export class SelectionExample extends React.Component {
139144 const selectedCells = selection . getSelectedCells ( )
140145 graph . removeCells ( selectedCells )
141146 } )
142- }
143-
144- refContainer = ( container : HTMLDivElement ) => {
145- this . container = container
146- }
147-
148- render ( ) {
149- return (
150- < div className = "x6-graph-wrap" >
151- < div ref = { this . refContainer } className = "x6-graph" />
152- </ div >
153- )
154- }
147+
148+ return ( ) => {
149+ graph . dispose ( )
150+ graphRef . current = null
151+ }
152+ } , [ ] )
153+
154+ return (
155+ < div className = "x6-graph-wrap" >
156+ < div ref = { containerRef } className = "x6-graph" />
157+ </ div >
158+ )
155159}
0 commit comments