首页 > 解决方案 > 将 Vis 网络与 React 集成的问题

问题描述

这里有没有人在任何项目中使用或使用过 Vis.js?我正在尝试将 Vis-network 与 React 集成,我什至设法做到了,但我无法以任何方式操纵它。

在 Vis.js 本身提供的示例中,它们使用同一 html 页面中的 javascript 代码来生成画布。在 React 中,我创建了一个 VisNetwork 组件,并在 App.js 中调用它来测试它。我什至设法生成了图像,它确实出现了,但我无法操纵它。

比如例子的canvas区域是600x400(例子链接),但是React生成的canvas区域是500x150。通过 App.css 我可以更改之前使用 100% 的宽度,但无法操纵高度。无论如何,我会把代码留在这里。

网络.js

import React, { Component, createRef } from "react";
import { DataSet, Network } from 'vis-network/standalone/umd/vis-network.min';

// Create an array with nodes
const nodes = new DataSet([
    {id: 1, label: 'Node 1'},
    {id: 2, label: 'Node 2'},
    {id: 3, label: 'Node 3'},
    {id: 4, label: 'Node 4'},
    {id: 5, label: 'Node 5'}
]);

// Create an array with edges
const edges = new DataSet([
    {from: 1, to: 3},
    {from: 1, to: 2},
    {from: 2, to: 4},
    {from: 2, to: 5}
]);

// Provide the data in the vis format
const data = {
  nodes: nodes,
  edges: edges
};

const options = {
    autoResize: true,
    height: '100%',
    width: '100%'
};

// Initialize your network!
class VisNetwork extends Component {
  constructor() {
    super();
    this.network = {};
    this.appRef = createRef();
  }

  componentDidMount() {
    this.network = new Network(this.appRef.current, data, options);
  }

  render() {
    return (
      <div ref={this.appRef} />
    );
  }
}

export default VisNetwork;

App.js中,我导入了 VisNetwork 并在 div 中调用它:

import React from 'react';
import './App.css';
import VisNetwork from './network';

function App() {
  return (
    <div className="App">
      <VisNetwork />
    </div>
  );
}

export default App;

应用程序.css

.App {
  text-align: center;
  width:500px;
  height:500px;
  border:solid;
  background-color:white;
}

请不要在没有回应的情况下否定这篇文章。它有害而不是帮助。谢谢。

标签: javascriptreactjs

解决方案


我建议设置选项宽度和高度 100% 不起作用的原因是网络附加在未定义高度和宽度的 div 上,因此您可以尝试以下代码:

const options = {
  autoResize: ture,
  height: '100%',
  width: '100%'
};

// Initialize your network!
class VisNetwork extends Component {
  constructor() {
  super();
  this.network = {};
  this.appRef = createRef();
}

componentDidMount() {
  this.network = new Network(this.appRef.current, data, options);

}




render() {

let containerStyle = {  //define container width and height.
   width:"500px",
   height:"500px",  
}

return (
   <div style={containerStyle} ref={this.appRef} />   
);
}
}

export default VisNetwork;

如果上面的代码不起作用,我建议使用this.network.setSize(width, height)强制画布改变。


推荐阅读