简体   繁体   中英

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. Since none of the Vis Network implementations work for me I have to use the plain library.

This is my test React component

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.

Another question is why isn't the ref not set and it's just <div> .

Because I thought that this.appRef = createRef(); in the constructor of the component and ref={this.appRef} in render() would lead to a ref.

调试器的屏幕截图

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM