react中使用antv g6的自上而下紧凑树

1、参考文档

首先确保安装antd g6

antv g6连接:AntV | 蚂蚁数据可视化 (antgroup.com)

在react中使用g6参照了文档中的例子:React 中使用 G6 | G6 (antgroup.com)

2、代码实现

2.1导入react和g6库,定义数据结构
import React from 'react';
import G6 from '@antv/g6';

const data={
  "id": "Modeling Methods",
  "children": [
    {
      "id": "Classification",
      "children": [
        {
          "id": "Logistic regression"
        },
        {
          "id": "Linear discriminant analysis"
        },
        {
          "id": "Rules"
        },
        {
          "id": "Decision trees"
        },
        {
          "id": "Naive Bayes"
        },
        {
          "id": "K nearest neighbor"
        },
        {
          "id": "Probabilistic neural network"
        },
        {
          "id": "Support vector machine"
        }
      ]
    },
    {
      "id": "Consensus",
      "children": [
        {
          "id": "Models diversity",
          "children": [
            {
              "id": "Different initializations"
            },
            {
              "id": "Different parameter choices"
            },
            {
              "id": "Different architectures"
            },
            {
              "id": "Different modeling methods"
            },
            {
              "id": "Different training sets"
            },
            {
              "id": "Different feature sets"
            }
          ]
        },
        {
          "id": "Methods",
          "children": [
            {
              "id": "Classifier selection"
            },
            {
              "id": "Classifier fusion"
            }
          ]
        },
        {
          "id": "Common",
          "children": [
            {
              "id": "Bagging"
            },
            {
              "id": "Boosting"
            },
            {
              "id": "AdaBoost"
            }
          ]
        }
      ]
    },
    {
      "id": "Regression",
      "children": [
        {
          "id": "Multiple linear regression"
        },
        {
          "id": "Partial least squares"
        },
        {
          "id": "Multi-layer feedforward neural network"
        },
        {
          "id": "General regression neural network"
        },
        {
          "id": "Support vector regression"
        }
      ]
    }
  ]
}
2.2创建React组件

这里使用的class组件

class MyGraphComponent extends React.Component {
  constructor(props) {
    super(props);
    this.containerRef = React.createRef();
    this.graphRef = React.createRef();
//通过React.createRef()方法创建了两个引用containerRef 和graphRef,用于引用组件中的容器元素和树形图实例。
  }

   componentDidMount() {
    this.buildTreeGrap()
//componentDidMount生命周期方法中调用了buildTreeGrap方法,用于初始化和渲染树形图。
  }

  
  buildTreeGrap(){
    const container = this.containerRef.current;
    const width = container.scrollWidth;
    const height = container.scrollHeight || 500;

    const graph = new G6.TreeGraph({
      container,
      width,
      height,
      linkCenter: true,
      modes: {
        default: [
          {
            type: 'collapse-expand',
            onChange: function onChange(item, collapsed) {
              // eslint-disable-next-line no-shadow
              const data = item.getModel();
              data.collapsed = collapsed;
              return true;
            },
          },
          'drag-canvas',
          'zoom-canvas',
        ],
      },
      defaultNode: {
        size: 26,
        anchorPoints: [
          [0, 0.5],
          [1, 0.5],
        ],
      },
      defaultEdge: {
        type: 'cubic-vertical',
      },
      layout: {
        type: 'compactBox',
        direction: 'TB',
        getId: function getId(d) {
          return d.id;
        },
        getHeight: function getHeight() {
          return 16;
        },
        getWidth: function getWidth() {
          return 16;
        },
        getVGap: function getVGap() {
          return 80;
        },
        getHGap: function getHGap() {
          return 20;
        },
      },
    });

    graph.node((node) => {
      let position = 'right';
      let rotate = 0;
      if (!node.children) {
        position = 'bottom';
        rotate = Math.PI / 2;
      }
      return {
        label: node.id,
        labelCfg: {
          position,
          offset: 5,
          style: {
            rotate,
            textAlign: 'start',
          },
        },
      };
    });

    graph.data(data);//将之前定义的数据应用到树形图中
    graph.render();
    graph.fitView();//使图形适应容器大小

    this.graphRef.current = graph;

    window.addEventListener('resize', this.handleResize);
  }


  componentWillUnmount() {
    window.removeEventListener('resize', this.handleResize);
    if (this.graphRef.current) {
      this.graphRef.current.destroy();
      this.graphRef.current = null;
    }
  }

//handleResize方法中处理页面resize事件,当页面大小变化时,调整树形图的大小以适应新的容器尺寸。
  handleResize = () => {
    const graph = this.graphRef.current;
    if (!graph || graph.get('destroyed')) return;
    const container = this.containerRef.current;
    if (!container || !container.scrollWidth || !container.scrollHeight) return;
    graph.changeSize(container.scrollWidth, container.scrollHeight);
  };

  render() {
    return <div ref={this.containerRef} style={{ height: '100%' }} />;
  }
}

export default MyGraphComponent;

这里使用的是文档给的数据,在使用该组件时可以传入数据替换。

  • 18
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
AntV X6 是一个基于 React 的可视化库,它提供了丰富的图形绘制、交互和布局功能,可以用于绘制各种类型的图表、流程图、组织结构图等。 使用 AntV X6 绘制图形需要引入相关的组件和样式,并创建一个画布元素。以下是一个简单示例: ```jsx import React, { useEffect, useRef } from 'react'; import { Graph } from '@antv/x6'; const MyGraph = () => { const container = useRef(null); useEffect(() => { const graph = new Graph({ container: container.current, width: 600, height: 400, }); const rect = graph.addNode({ x: 100, y: 100, width: 80, height: 40, label: 'Hello', style: { fill: '#eee', stroke: '#333', strokeWidth: 1, }, }); const circle = graph.addNode({ x: 300, y: 200, width: 40, height: 40, shape: 'ellipse', label: 'World', style: { fill: '#ccc', stroke: '#666', strokeWidth: 2, }, }); graph.addEdge({ source: rect, target: circle, attrs: { line: { stroke: '#333', strokeWidth: 1, }, }, }); }, []); return <div ref={container} />; }; export default MyGraph; ``` 在上面的示例,我们创建了一个名为 `MyGraph` 的组件,使用 `useRef` 创建了一个画布元素的引用 `container`,并在 `useEffect` 创建了一个 `Graph` 实例并添加了两个节点和一条边。 节点的属性包括位置、大小、形状、标签和样式等,可以根据具体需要进行调整。边的属性包括起点、终点和样式等。 在实际使用,可以根据业务需求和数据结构进行更复杂的图形绘制和交互操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值