Can react be used with g6?

藏色散人
Release: 2022-12-20 17:09:54
Original
2584 people have browsed it

react can use g6. How to use it: 1. Introduce AntV G6 into the project through the "npm install --save @antv/g6" command; 2. Use "yarn install" to reload the dependencies; 3. Just introduce G6 into the js file that needs to use G6.

Can react be used with g6?

#The operating environment of this tutorial: Windows 10 system, react18 version, Dell G3 computer.

Can react use g6?

can be used.

Using AntV G6 in React

AntV G6: G6 is a simple, easy-to-use, and complete graph visualization engine. It provides A series of elegantly designed and easy-to-use graph visualization solutions. It can help developers build their own graph visualization, graph analysis, or graph editor applications. Official website

Introduction of AntV G6

Use npm to introduce the package in the project

npm install --save @antv/g6
Copy after login

Reload dependencies

yarn install
Copy after login

In the js file that needs to use G6 After introducing G6

import G6 from '@antv/g6';
Copy after login

, the preparation work is over. Let’s start using G6 to draw the required relationship diagram, taking the force-directed diagram as an example to describe one-to-many and one-to-one relationships.

Use of AntV G6

Create a container: Create a container in HTML to accommodate the diagram drawn by G6, usually a div tag. When G6 draws, it will append the canvas tag under the container, and then draw the image in it.

ref: In React, you can get the real DOM element through ref.current. Forwarding Refs (Official Document)

<div ref={ref} id="test"/>
Copy after login

Creating a relationship diagram: When creating a relationship diagram (instantiation), at least the container, width and height need to be set for the diagram. For the rest, please refer to the API corresponding to the legend and the official API document to configure as needed.

   graph = new G6.Graph({
     container: ref.current,
     width: width < 1000 ? 387 : width,
     height: width < 1000 ? 220 : 550,
     layout: {
       type: &#39;force&#39;,
       preventOverlap: true,
       linkDistance: (d) => {
         if (d.source.id === &#39;node0&#39;) {
           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: &#39;#5B8FF9&#39;,
     },
     edgeStateStyles: {
       highlight: {
         stroke: &#39;#5B8FF9&#39; // 这个颜色可以根据个人喜好进行修改
       }
     },
     modes: {
       default: [&#39;drag-canvas&#39;, &#39;zoom-canvas&#39;],
     },
   });
Copy after login

Data processing and preparation: Process the data according to the data format of the required chart.

Configure the data source and render:

graph.data(data); // 读取 Step 2 中的数据源到图上
graph.render(); // 渲染图
Copy after login

After explaining the basic use of AntV G6, you need to note that in React, G6 is different from AntV L7 and AntV G2, BizCharts, AntV G6 is You need to access nodes during use. When using its graph as a component, if you ignore this, problems will occur. Using G6 in React (official website document)

AntV G6 Note in React

  • Return the Demo that renders G6 graphics as an anonymous function, and at the same time The function return should be the container created above, which is used as a component when calling Demo in other js files, and the parameters passed in are the formal parameters of the anonymous function.

  • The instance generated in the second step above: "Create the relationship diagram" should be defined in the side effect useEffect.

  • Due to obtaining data in CompotentDidMount, when rendering the Demo, there may be data that does not receive a response before rendering the Demo, resulting in an error. The solution is as follows:

{deviceData.length ? <G6Picture g6Data={deviceData}/> : <></>}
Copy after login

Achieve the effect

Can react be used with g6?

The complete code and partial explanation are as follows:

Demo.js

import G6 from &#39;@antv/g6&#39;;
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 <>
    <div ref={ref} id="test"/>
  ;
};
Copy after login

Specific use of Demo’s js file :

import G6Picture from './Demo'
render(
    return(
        <>
            {deviceData.length ? <G6Picture g6Data={deviceData}/> : <></>}
        
    )
)
Copy after login

Recommended learning: "react video tutorial"

The above is the detailed content of Can react be used with g6?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!