react-graph-vis 实现拓扑图
2024-01-03 本文已影响0人
小碎步快跑
由于项目需求简单,所以使用了一个 react-graph-vis组件:GitHub - crubier/react-graph-vis: A react component to render nice graphs using vis.js
实际就是基于vis.js封装的 ,详细文档参考官网:vis.js - Network documentation. (visjs.github.io)
需要安装的依赖:npm i react-graph-vis
react项目实现代码:
import Graph from "react-graph-vis";
export default function index() {
const [graph, setGraph] = useState({ nodes: [], edges: [] });
const htmlTitle = (text) => {
const container = document.createElement("div");
container.innerHTML = text;
return container;
};
//基本配置信息
const options = {
autoResize: true,
height: "100%",
width: "100%",
interaction: {
hover: true,
hoverConnectedEdges: true,
multiselect: true,
},
nodes: {
shape: "image",
brokenImage: "{{ broken_image }}" ?? "",
size: 35,
font: {
multi: "md",
face: "helvetica",
color:
document.documentElement.dataset.netboxColorMode === "dark"
? "#fff"
: "#000",
},
},
edges: {
length: 100,
width: 2,
font: {
face: "helvetica",
},
shadow: {
enabled: true,
},
},
// physics: {
// solver: "forceAtlas2Based",
// },
};
// 事件
const events = {
select: function (event) {
var { nodes, edges } = event;
if (nodes) {
//点击单个节点页面跳转
history.push({
pathname: "/XXXX/detail",
search: `?id=${nodes}`,
});
}
},
showPopup: (id) => {
// node id
const data = graph.nodes.map((el) => {
if (el.id === id) {
el.label = `sample node name`;
}
return el;
});
setGraph({ ...graph, nodes: data });
},
dragEnd: (params) => {
console.log(params);
},
};
return (
<div className="data-container">
<div
style={{
height: "100%",
border: "1px solid #CCC",
borderRadius: "7px ",
}}
>
<Graph graph={graph} options={options} events={events} />
</div>
</div>
);
}
graph 数据是从接口获取的,格式如下:
//不能完全复制,参考思路即可
{
"nodes": [
{
"id": 86,
"color.border": "#9e9e9e",
"physics": true,
"x": 0,
"y": 0,
"title": "<table><tbody> <tr><th>Type: </th><td>hello</td></tr><tr><th></tbody></table>",
"name": "172.0.1.1",
"label": "172.0.1.1",
"shape": "image",
"href": "/XXX/",
"image": "/img/server1.svg"
},
{
"id": 87,
"color.border": "#9e9e9e",
"physics": true,
"x": 0,
"y": 0,
"title": "<table><tbody> <tr><th>Type: </th><td>hello</td></tr><tr><th></tbody></table>",
"name": "172.0.1.22",
"label": "172.0.1.22",
"shape": "image",
"href": "/XXX/",
"image": "/img/server2.svg"
}
],
"edges": [
{
"id": 1,
"from": 86,
"to": 87,
"color": "#2b7ce9",
"title": "Cable betweenXXX",
"href": "/XXX/cables/1/"
}
],
"group": "default"
}
//获取接口后对数据进行了整理
const json = JSON.parse(res.data.topology_data);
json.nodes = json.nodes.map((item) => ({
...item,
image: "/net-api" + item.image,
title: htmlTitle(item.title),
}));
setGraph(json);