[英]How to access properties of objects from a third-party DOM library used in a React component from the outside
I want to use Vis.js in a React based project. 我想在基于React的项目中使用Vis.js。 Since none of the Vis Network implementations work for me I have to use the plain library.
由于Vis Network的实现都不适合我,因此我必须使用普通库。
This is my test React component 这是我测试的React组件
import { DataSet, Network } from 'vis';
import React, { Component, createRef } from "react";
class VisNetwork extends Component {
constructor() {
super();
this.network = {};
this.appRef = createRef();
this.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' }
]);
this.edges = new DataSet([
{ from: 1, to: 3 },
{ from: 1, to: 2 },
{ from: 2, to: 4 },
{ from: 2, to: 5 }
]);
this.data = {
nodes: this.nodes,
edges: this.edges
};
this.options ={};
}
componentDidMount() {
this.network = new Network(this.appRef.current, this.data, this.options);
}
render() {
return (
<div ref={this.appRef} />
);
}
}
export default VisNetwork;
It's the only component mounted so far 这是迄今为止唯一安装的组件
ReactDOM.render(<VisNetwork />,document.getElementById('mynetwork'));
My question is how I can access the properties of the network, for example, to get or delete a node. 我的问题是如何访问网络的属性,例如获取或删除节点。
node = nodes.get(nodeId);
I read about React Ref and tried something like () =>{ console.log(document.getElementsByClassName('vis-network'))
as callback of ReactDOM.render()
but that doesn't help. 我阅读了有关React Ref的文章,并尝试了类似
() =>{ console.log(document.getElementsByClassName('vis-network'))
作为ReactDOM.render()
回调, ReactDOM.render()
没有帮助。
Another question is why isn't the ref not set and it's just <div>
. 另一个问题是为什么没有设置ref,而只是
<div>
。
Because I thought that this.appRef = createRef();
因为我认为
this.appRef = createRef();
in the constructor of the component and ref={this.appRef}
in render() would lead to a ref. 在组件的构造函数中,而render()中的
ref={this.appRef}
将导致引用。
I hope you can give me a hint. 希望您能给我提示。
Actually the flow should be the other way round, define the nodes outside of the component, then pass them in. For that define the constructor as: 实际上,流程应该是相反的,在组件外部定义节点,然后将其传递。为此,将构造函数定义为:
constructor(props) {
super(props);
this.nodes = props.nodes;
//...
}
Then construct it as: 然后将其构造为:
const nodes = new DataSet([/*...*/]);
ReactDOM.render(<VisNetwork nodes={nodes} />,document.getElementById('mynetwork'));
Note that you should put anything stateful into this.state
and use setState
to mutate it. 请注意,您应该将有状态的任何内容放入
this.state
并使用setState
进行突变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.