1

当我尝试更新悬停事件的状态时,实际状态值正在更改,但图形没有重新渲染。

在控制台中,我可以看到节点标签已更改为示例。但图表没有重新渲染。

这是我的基于反应功能的组件。

import React, { useEffect, useState } from 'react';
import Graph from 'react-graph-vis';

import './vis-network.css';

function RelationGraph1() {
  const [graph, setGraph] = useState({
    nodes: [
      {
        id: 1,
        label: 'Node 1',
        title: '',
      },
      { id: 2, label: 'Node 2', title: '' },
      { id: 3, label: 'Node 3', title: '' },
      { id: 4, label: 'Node 4', title: '' },
      { id: 5, label: 'Node 5', title: '' },
    ],
    edges: [
      { from: 1, to: 2 },
      { from: 1, to: 3 },
      { from: 2, to: 4 },
      { from: 2, to: 5 },
    ],
  });

  const options = {
    layout: {
      hierarchical: false,
    },
    edges: {
      color: '#1D1D1D',
    },
    interaction: {
      hover: true,
      navigationButtons: true,
      tooltipDelay: 0,
    },
    nodes: {
      borderWidth: 0,
      borderWidthSelected: 0,
      color: '#0262C4',
      shape: 'circle',
      size: 1,
      shadow: {
        enabled: true,
        color: 'rgba(0,0,0,0.5)',
        size: 10,
        x: 5,
        y: 5,
      },
      font: {
        color: '#fff',
        size: 13,
        bold: {
          mod: 'bold',
        },
      },
    },
  };

  const events = {
    select: function (event) {
      var { nodes, edges } = event;
      console.log('Selected nodes:');
      console.log(nodes);
      console.log('Selected edges:');
      console.log(edges);
    },
    showPopup: (id) => { // node id
      const data = graph.nodes.map((el) => {
        if (el.id === id) {
          el.label = `sample node name`;
        }
        return el;
      });
      setGraph({ ...graph, nodes: data });
    },
  };

  return (
    <Graph
      graph={graph}
      options={options}
      events={events}
      style={{ height: '450px' }}
    />
  );
}

export default RelationGraph1;

真的很感激帮助。谢谢 !

4

1 回答 1

1

我能够像这样更新 hoverNode 事件中的标签:

    hoverNode: (e) => {
      const data = graph.nodes.map((el) => {
        if (el.id === e.node) return { ...el, label: "sample node name" };
        else return el;
      });

      const temp = { ...graph };
      temp.nodes = data;
      setGraph(temp);
    },

示例:https ://codesandbox.io/s/long-bird-4h444?file=/src/App.js:1235-1501

于 2021-02-03T10:49:21.890 回答