如何从外部访问 React 组件中使用的第三方库 DOM 对象的属性

How to access properties of objects from a third-party DOM library used in a React component from the outside

我想在基于 React 的项目中使用 Vis.js。由于 none 的 Vis Network 实现对我有用,所以我必须使用普通库。

这是我的测试 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;

这是目前唯一安装的组件

ReactDOM.render(<VisNetwork />,document.getElementById('mynetwork'));

我的问题是如何访问网络的属性,例如,获取或删除节点。

node = nodes.get(nodeId);

我阅读了 React Ref 并尝试了类似 () =>{ console.log(document.getElementsByClassName('vis-network')) 作为 ReactDOM.render() 的回调,但这无济于事。

另一个问题是为什么没有设置 ref 而只是 <div>.

因为我认为组件构造函数中的 this.appRef = createRef(); 和 render() 中的 ref={this.appRef} 会导致 ref.

希望大家多多指教

实际上流程应该是相反的,在组件外部定义节点,然后将它们传入。为此,将构造函数定义为:

 constructor(props) {
    super(props);
    this.nodes = props.nodes;
    //...
}

然后构造为:

 const nodes = new DataSet([/*...*/]);
 ReactDOM.render(<VisNetwork nodes={nodes} />,document.getElementById('mynetwork'));

请注意,您应该将任何有状态的内容放入 this.state 并使用 setState 对其进行变异。