ReactJS中VisJS网络图画布添加多节点框选择器

IT技术 javascript reactjs canvas vis.js vis.js-network
2021-05-24 14:00:21

例子

下面是网络上画布画布选择多个节点的jQuery示例:

如何将其转换为 React?

沙盒

在这个沙箱中设置react-graph-vis),并添加了对图表的引用:https : //codesandbox.io/s/5m2vv1yo04

尝试

  • 在 '' 上使用 React.createRef() 将 eventLisnters 添加到 Graph/canvas
  • 在画布上使用此方法时遇到问题: .getContext("2d")
  • 我觉得我不明白如何访问这里提到react-graph-vis方法

最终目标

  • 在左键单击 + 鼠标拖动时绘制框选择器
  • on mouseup,在画布上绘制的框中选择节点,并清除绘制

也许我在这方面走错了方向。

2个回答

我使用您共享的 JSSampler 示例将其放在一起。

解决方案

You just needed to use the ref to connect the Network and canvas. Everything else pretty much fell into place. https://codesandbox.io/s/5m2vv1yo04

Cleanup suggestions

  • move global variables into react class
  • split VisJS highlight code into own file

vis.js docs reveal that the Network object has methods exposed (http://visjs.org/docs/network). react-graph-vis shows that you can get access to these methods by passing in a callback to the getNetwork prop of Graph. That callback will be invoked with a reference to the underlying Network object at which point you should assign that argument to a class property as described by @Irecknagel in the Github issue.

Adding a ref to the Graph component as you are doing wraps the Component. However, it will not necessarily provide a reference to the Network because the Network is an object constructed by the Graph component.

In regards to adding event listeners, the react-graph-vis demo source code might help. They define their event listeners as an object and then pass it in as a prop like so.

// in render or elsewhere depending on scoping needs
const events = {
  select: function(event) {
    var { nodes, edges } = event;
    console.log("Selected nodes:");
    console.log(nodes);
    console.log("Selected edges:");
    console.log(edges);
  }
};
// return of render
<Graph graph={graph} options={options} events={events} style={{ height: "640px" }} />

Due to my lack of familiarity with the packages, I'm not sure what the end goal of calling .getContext("2d") is. I'm not sure if your defined 'end goals' are within the scope of the packages you're using.