react能用g6嗎

藏色散人
發布: 2022-12-20 17:09:54
原創
2470 人瀏覽過

react能用g6,其使用方法:1、透過「npm install --save @antv/g6」指令在專案中引入AntV G6;2、使用「yarn install」重新載入依賴;3、在需要使用到G6的js檔案中引入G6即可。

react能用g6嗎

本教學操作環境:Windows10系統、react18版、Dell G3電腦。

react能用g6嗎?

能用。

React中使用AntV G6

AntV G6:G6 是一個簡單、易用、完備的圖視覺化引擎,它在高定制能力的基礎上,提供了一系列設計優雅、便於使用的圖視覺化解決方案。能幫助開發者建構屬於自己的圖視覺化、圖分析、或圖編輯器應用。官網

AntV G6的引入

專案中使用npm對套件引入

npm install --save @antv/g6
登入後複製

重新載入依賴

yarn install
登入後複製

在需要使用到G6的js文件中引入G6

import G6 from '@antv/g6';
登入後複製

自此,準備工作結束,以下開始使用G6繪製所需的關係圖,以力導向圖為例描述一對多、一對一的關係。

 AntV G6的使用

建立容器:在 HTML 中建立一個用於容納 G6 繪製的圖的容器,通常為 div 標籤。 G6 在繪製時會在該容器下方追加 canvas 標籤,然後將圖繪製在其中。

ref:在 React 中,可以透過ref.current取得到真實的 DOM 元素。 Forwarding Refs(官方文件)

登入後複製

建立關係圖:建立關係圖(實例化)時,至少需要為圖表設定容器、寬度和高度。其餘請參考圖例對應的API以及官方API文檔,按需配置。

   graph = new G6.Graph({
     container: ref.current,
     width: width < 1000 ? 387 : width,
     height: width < 1000 ? 220 : 550,
     layout: {
       type: 'force',
       preventOverlap: true,
       linkDistance: (d) => {
         if (d.source.id === 'node0') {
           return 10;
         }
         return 80;
       },
       nodeStrength: (d) => {
         if (d.isLeaf) {
           return 200;
         }
         return -500;
       },
       edgeStrength: (d) => {
         if (d.source.edgeStrength) {
           return 0.1;
         }
         return 0.8;
       },
     },
     defaultNode: {
       color: '#5B8FF9',
     },
     edgeStateStyles: {
       highlight: {
         stroke: '#5B8FF9' // 这个颜色可以根据个人喜好进行修改
       }
     },
     modes: {
       default: ['drag-canvas', 'zoom-canvas'],
     },
   });
登入後複製

資料處理及準備:根據所需圖表的資料格式,對資料進行處理。

配置資料來源並渲染:

graph.data(data); // 读取 Step 2 中的数据源到图上
graph.render(); // 渲染图
登入後複製

AntV G6的基本使用闡述完後,需要注意在React中,G6與AntV L7及AntV G2,BizCharts有所不同,AntV G6在使用過程中需要存取節點,將其圖形作為組件使用時,如果忽略這一點,則會出現問題。 React中使用G6(官網文檔)

AntV G6在React中註意

  • 將渲染G6圖形的Demo作為匿名函數返回,同時函數return的應為上文所建立的容器,在其他js檔案中呼叫Demo時作為元件,同時傳入的參數為匿名函數的形參。

  • 上文中第二步:「建立關係圖」中產生的實例應在副作用useEffect中定義。

  • 由於在CompotentDidMount中獲取數據,當渲染Demo時可能會存在數據並未得到響應便渲染Demo導致報錯,解決辦法如下:

#
{deviceData.length ?  : <>}
登入後複製

實作效果

react能用g6嗎

完整程式碼及部分解釋如下:

Demo.js

import G6 from '@antv/g6';
import React, {useEffect} from "react";
import groupBy from 'lodash/groupBy'
import router from "umi/router";
function dealData(data) {//数据处理函数
  const dataGroup = groupBy(data, (item) => [item.chipGroupName])
  const nodes = [];
  const edges = [];
  let index = 0;
  nodes.push({id: `node${index}`, size: 90, label: "芯片组管理", edgeStrength: true})
  for (const key in dataGroup) {
    index += 1;
    nodes.push({id: `node${index}`, size: 60, label: key, edgeStrength: false, isLeaf: true})
    edges.push({source: `node0`, target: `node${index}`, label: '芯片', routerFlag: 0})
    if (dataGroup[key]) {
      const indexTemp = index;
      dataGroup[key].map((item) => {
        index += 1;
        nodes.push({id: `node${index}`, size: 40, label: item.name, edgeStrength: false})
        edges.push({source: `node${indexTemp}`, target: `node${index}`, label: "产品", routerFlag: 1})
      })
    }
  }
  const returnData = {
    nodes: [...nodes],
    edges: [...edges],
  }
  return returnData;
}
export default function (props) {//props为传入的参数
  const ref = React.useRef(null)
  let graph = null;
  useEffect(() => {
    const {g6Data} = props;
    const data = dealData(g6Data);
    const width = document.getElementById('test').clientWidth;//获取当前宽度
    if (!graph) {
      graph = new G6.Graph({//生成关系图实例
        container: ref.current,//获取真实的DOM节点
        width: width < 1000 ? 387 : width,//根据所需大小定义高度、宽度
        height: width < 1000 ? 220 : 550,
        layout: {//根据要求所需及官方API文档配置
          type: 'force',
          preventOverlap: true,
          linkDistance: (d) => {
            if (d.source.id === 'node0') {
              return 10;
            }
            return 80;
          },
          nodeStrength: (d) => {//根据要求所需及官方API文档配置
            if (d.isLeaf) {
              return 200;
            }
            return -500;
          },
          edgeStrength: (d) => {//根据要求所需及官方API文档配置
            if (d.source.edgeStrength) {
              return 0.1;
            }
            return 0.8;
          },
        },
        defaultNode: {//根据要求所需及官方API文档配置
          color: '#5B8FF9',
        },
        edgeStateStyles: {//根据要求所需及官方API文档配置
          highlight: {
            stroke: '#5B8FF9' // 这个颜色可以根据个人喜好进行修改
          }
        },
        modes: {//根据要求所需及官方API文档配置
          default: ['drag-canvas', 'zoom-canvas'],
        },
      });
    }
    const {nodes} = data;
    graph.data({//绑定数据
      nodes,
      edges: data.edges.map((edge, i) => {
        edge.id = `edge${i}`;
        return Object.assign({}, edge);
      }),
    });
    graph.render();//渲染图形
//下面为交互事件配置及操作函数
    graph.on('node:dragstart', (e) => {
      graph.layout();
      refreshDragedNodePosition(e);
    });
    graph.on('node:drag', (e) => {
      refreshDragedNodePosition(e);
    });
    graph.on('node:dragend', (e) => {
      e.item.get('model').fx = null;
      e.item.get('model').fy = null;
    });
    graph.zoom(width < 1000 ? 0.7 : 1, {x: 300, y: 300});
    graph.on('node:mouseenter', (ev) => {
      const node = ev.item;
      const edges = node.getEdges();
      const model = node.getModel();
      const size = model.size * 1.2;
      graph.updateItem(node, {
        size,
      });
      edges.forEach((edge) => {
        graph.setItemState(edge, 'highlight', true)
      });
    });
    graph.on('node:click', (e) => {
      router.push({pathname: `/DeviceSetting/ChipsetManagement`})
    });
    graph.on('node:mouseleave', (ev) => {
      const node = ev.item;
      const edges = node.getEdges();
      const model = node.getModel();
      const size = model.size / 1.2;
      graph.updateItem(node, {
        size,
      });
      edges.forEach((edge) => graph.setItemState(edge, 'highlight', false));
    });
    function refreshDragedNodePosition(e) {
      const model = e.item.get('model');
      model.fx = e.x;
      model.fy = e.y;
    }
  }, []);
  return <>
    
; };
登入後複製

具體使用Demo的js文件:

import G6Picture from './Demo'
render(
    return(
        <>
            {deviceData.length ?  : <>}
        
    )
)
登入後複製

推薦學習:《react影片教學

以上是react能用g6嗎的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!