2017-10-20 5 views
0

私は、反応でcytoscapejsで可視化された、ノードマップを作成しようとしています。 次のコードを実行しようとすると、「this.handleTextChangeは関数ではありません」というエラーが表示されます。
const内から関数を呼び出すことはできませんか?コンパイルは正常ですが、ノードをクリックするとエラーが発生します。CytoscapeJSはsetState関数を呼び出しています

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>; 
    } 
} 

状態を設定せずにこの問題を回避する方法はありますか?

+0

'componentDidMount'をバインドする必要はありません。また、「エラーが発生しました」、どちらですか? – JulienD

答えて

1

1)これにcomponentDidMountをバインドする必要はありません。だから、)以下

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

2を除去字句これを結合するために矢印関数を使用し、この値は、矢印関数が定義されたコンテキストと同じままです。だから、別に以下の

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

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

に変更します(ノードで持つEventEmitter、jQueryのリスナー、またはCytoscapeなど)ほとんどのエミッタがエミッタオブジェクトへのコールバックにthisを設定するFunction.apply()を使用しようとしている---理由であります(2)が必要である。

関連する問題