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;

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

### 集成 AntVReact 项目 为了在 React 项目中集成并使用 AntV 进行数据可视化,可以遵循以下方法: #### 安装依赖包 首先,在命令行工具中进入项目的根目录下安装 `@antv/g2` 或者其他所需的 AntV 组件库。 ```bash npm install @antv/g2 --save ``` 这一步骤会下载必要的文件到 node_modules 文件夹内,并更新 package.json 中的 dependencies 字段[^2]。 #### 创建图表组件 接着创建一个新的 React 组件来承载 AntV 图表实例。这里以柱状图为例子展示基本结构: ```jsx import React, { useEffect, useRef } from 'react'; // 导入 G2 import { Chart } from '@antv/g2'; const BarChart = ({ data }) => { const chartRef = useRef(null); useEffect(() => { if (!chartRef.current) return; // 初始化图表配置 const chart = new Chart({ container: chartRef.current, width: 600, height: 300 }); // 设置数据源 chart.data(data); // 定义坐标轴映射关系 chart.interval().position('genre*sold'); // 渲染图表 chart.render(); // 销毁旧图表防止内存泄漏 return () => chart.destroy(); }, [data]); return ( <div ref={chartRef}></div> ); }; export default BarChart; ``` 上述代码展示了如何通过 React hooks 和 DOM 引用来管理 AntV 图表生命周期的方法。 #### 使用封装好的标题组件 对于需要重复使用的 UI 元素比如图表上方的文字说明部分,则可以根据实际情况复用之前提到过的 `<Title />` 组件[^4]。 ```jsx <Title title="销售统计"/> <BarChart data={salesData} /> ``` 这样不仅提高了代码重用率还增强了维护性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值