react + typescript 中使用 G6

G6的官方文档中写了graph的各种用法,都是以js方式编写,在 拓展阅读 中有提供 react 中使用 G6 的 demo,可以参考。React 中使用 G6

近期尝试了一下在 react + typescript 中使用 G6,因为 typescript 中有变量的类型定义,所以在定义变量时需要注意其类型

最初将官方中的案例抠下来放入项目中,就会报出类型错误
在这里插入图片描述
(只需要在定义 ref 时,给 ref 定义一个类型就可以了:const ref: any = React.useRef(null)

在这里插入图片描述
(只需要在定义 graph 时,给 graph 定义一个类型就可以了:let graph: any = null

import React, { useEffect } from 'react';
import ReactDOM from 'react-dom';
import { Button } from 'antd'
import G6 from '@antv/g6';

const treeData = {
  id: 'root',
  label: 'Root',
  children: [
    {
      id: 'SubTreeNode1',
      label: 'subroot1',
      children: [
        {
          id: 'SubTreeNode1.1',
          label: 'subroot1.1',
        }
      ]
    },
    {
      id: 'SubTreeNode2',
      label: 'subroot2',
      children: [
        {
          id: 'SubTreeNode2.1',
          label: 'subroot2.1',
        },
        {
          id: 'SubTreeNode2.2',
          label: 'subroot2.2',
        }
      ]
    } 
  ]
};

const TreeGraphReact = () => {
  const ref: any = React.useRef(null)	// 给 ref 设置一个any类型解决 container 报错
  let graph: any = null		// 给 graph 设置一个any类型 解决 new G6.Graph 时赋值问题

  useEffect(() => {
    if(!graph) {

      graph = new G6.TreeGraph({
        container: ref.current,   // 指定挂载容器
        width: 800,   // 图的宽度
        height: 500,    // 图的高度
        fitView: true,  // 是否将图适配到画布大小,可以防止超出画布或留白太多。
        modes: {
          default: ['drag-canvas']
        },
        defaultEdge: {
          shape: 'cubic-horizontal',
          style: {
            stroke: '#A3B1BF'
          }
        },
        defaultNode: {
          shape: 'rect',
          labelCfg: {
            style: {
              fill: '#000000A6',
              fontSize: 10
            }
          },
          style: {
            stroke: '#72CC4A',
            width: 150
          }
        },
        layout: {
          type: 'dendrogram', // 布局类型
          direction: 'TB',    // 自左至右布局,可选的有 H / V / LR / RL / TB / BT
          nodeSep: 50,      // 节点之间间距
          rankSep: 200      // 每个层级之间的间距
        }
      })
    }
    graph.data(treeData)	// 加载数据
    graph.render()	// 渲染
  }, [])

  const handleChangeData = () => {
    const node = graph.findById('SubTreeNode1')
    graph.updateItem(node, {
      label: 'xxx',
      style: {
        fill: 'red'
      }
    })
  }

  return (
    <div ref={ref}>
      <Button onClick={handleChangeData} type='primary'>更新数据源</Button>
    </div>
  );
}

export default TreeGraphReact
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值