CytoscapeJS 在 React 中调用 setState 函数

CytoscapeJS calling setState function in React

我正在尝试制作一个节点图,用反应中的 cytoscapejs 可视化。 当尝试 运行 以下代码时,我收到错误 "this.handleTextChange is not a function".
是否不允许从 const 中调用函数?编译正常,但是点击节点的时候就报错

import React from 'react';
const cytoscape = require( 'cytoscape' );
const cycola = require( 'cytoscape-cola' );

cytoscape.use( cycola );

export class NodeBox extends React.Component {
    constructor( props ) {
        super( props );
        this.componentDidMount = this.componentDidMount.bind( this );
        this.state = {
         description: ''
      }

      this.handleTextChange = this.handleTextChange.bind(this);

    }
    handleTextChange(text){
      this.setState({description: text});
    }

    componentDidMount() {

        const cy = cytoscape( {

            container: document.getElementById( 'cy' ),
            boxSelectionEnabled: false,
            elements: this.props.elements[0],
            style: cytoscape.stylesheet()
              .selector('node')
                .css({
                  'label': 'data(name)',
                  'width':'data(size)',
                  'height':'data(size)',
                  'border-width':'3',
                  'border-color': '#618b25',
                  'background-fit':'cover',
                  'background-image': 'data(img)'

                })

              .selector('edge')
                .css({
                  'curve-style': 'unbundled-bezier',
                  'control-point-distance': '20px',
                  'control-point-weight': '0.5', // '0': curve towards source node, '1': towards target node.
                  'width': 1, //
                  'line-color': '#618B25',
                  'target-arrow-color': '#618B25',
                  'target-arrow-shape': 'triangle'
                })


          },
          'layout':{
            'name': 'cola', 'maxSimulationTime': 0
          }

      );

      cy.panningEnabled( false );

      cy.on('tap', 'node', function(evt){
          var node = evt.target;
          if (node.id() !== 1){
            console.log(node.data('description'));

            this.handleTextChange(node.data('description'));
          }
        });
      cy.panningEnabled( false );
    }
    render() {
        return <div> <div style ={{'height':300, 'width':'100%'}} id="cy"> </div><h1 id="desc" style={{textAlign:"center"}}>{this.state.description}</h1></div>;
    }
}

有没有其他方法可以在不设置状态的情况下解决这个问题?

1) 您不需要将 componentDidMount 绑定到此。因此,删除以下内容

this.componentDidMount = this.componentDidMount.bind( this );

2) 使用箭头函数词法绑定this,this的值与定义箭头函数的上下文保持一致。所以,改成下面的

cy.on('tap', 'node',(evt) => {
      var node = evt.target;
      if (node.id() !== 1){
        console.log(node.data('description'));

        this.handleTextChange(node.data('description'));
      }
});

旁白:大多数发射器(如 Node 中的 EventEmitter、jQuery 侦听器或 Cytoscape)将使用 Function.apply() 在发射器对象的回调中设置 this -- - 这就是为什么 (2) 是必要的。