2017-03-17 63 views
0

我正嘗試在React應用程序中使用d3.js。React組件功能無法調用另一個功能

this.animateFirstStep在componentDidMount中被調用的很好,但在animateFirstStep中調用的時候,this.animateSecondStep永遠不會被調用。

import React, { Component, PropTypes } from 'react'; 

var d3 = require("d3"); 

export default class App extends Component { 

    constructor() { 
     super(); 
     this.state = {}; 
    } 

    animateFirstStep() { 
     d3.select(this) 
      .transition() 
      .delay(0) 
      .duration(1000) 
      .attr("r", 10) 

這一個不被調用

  .on("end", this.animateSecondStep); 
    } 

    animateSecondStep() { 
     console.log("hello"); 
     d3.select(this) 
      .transition() 
      .duration(1000) 
      .attr("r", 40); 
    } 

    componentDidMount() { 
     this.sampleSVG = d3.select(".d3") 
      .append("svg") 
      .attr("width", 100) 
      .attr("height", 100); 

     this.sampleSVG.append("circle") 
      .style("stroke", "gray") 
      .style("fill", "white") 
      .attr("r", 40) 
      .attr("cx", 50) 
      .attr("cy", 50) 
      .on("mouseover", function(){d3.select(this).style("fill", "aliceblue");}) 
      .on("mouseout", function(){d3.select(this).style("fill", "white");}) 

調用此細

  .on("mousedown", this.animateFirstStep); 
    } 

    render() { 
     return (<div className="d3"></div>); 
    } 
} 
+0

你可以嘗試添加this.animateFirstStep = this.animateFirstStep.bind(this); this.animateSecondStep = this.animateSecondStep.bind(this)在構造函數中並重試?不確定是否是這種情況,但是您在該功能中指的是「this」。 – MattYao

+0

嘗試:'.on(「end」,this.animateSecondStep.bind(this));' –

+1

打開chrome檢查器,轉到「sources」選項卡,單擊「暫停異常」,然後選中「暫停捕獲異常「 –

回答

1

d3.select方法需要一個DOM元素。在類方法中,this指向React組件的實例,而不是相應的元素。您應該使用ref先獲取鏈接的dom元素,然後將其傳遞給select方法。

+0

是的,這是問題所在。我剛剛將animateFirstStep和animateSecondStep移動到另一個文件,並在React Component中調用它們,並且它工作正常。 – HaseebR7