2017-03-17 94 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