如何在函数中以此指向React组件?

时间:2018-07-20 02:56:06

标签: javascript reactjs d3.js this react-component

我正在尝试创建一个集成了D3.js和React的填充物规。首先,请在下面查看我的代码:

componentDidMount() {
  renderOuterGauge();
  renderInnerGauge();
}

componentDidUpdate() {
  renderOuterGauge();
}

renderInnerGauge = () => {
  const innerGauge = this.svg.append('path')
    .attr('transform', 'translate(60,100)')
    .attr('stroke', 'transparent')
    .attr('d', 'M0,0 l440,-60 v100 h-440 v-40')
    .on('click', function(d) {
      const x = d3.mouse(this)[0];
      const yUP = x / (440 / -60);
      const score = x / 4.38;
      console.log(score);
      this.setState({
        score: score
      })
      d3.event.this.setAttribute('d', `M0,0 l${x},${yUP} v${yUP+40} h${-x} v-40`);
      d3.event.this.setAttribute('fill', 'forestgreen');
    })
}

如上所述,我正在尝试使用this.setState方法动态填充内部仪表,但是由于该方法调用处于闭包状态,因此无法在setState上使用this

通常,我可以使用箭头函数定义来解决此问题,但是据我所知,为了使用量规中的x获得yd3.mouse(this)的值,我无法使用箭头功能。在这种情况下,是否可以将this指向react组件并在同一函数中使用mouse方法?

2 个答案:

答案 0 :(得分:2)

您的意思是这样的吗?在进入闭包之前,只需将this指向变量。

renderInnerGauge = () => {

    const self = this

    const innerGauge = this.svg.append('path')
            .attr('transform','translate(60,100)')
            .attr('stroke','transparent')
            .attr('d','M0,0 l440,-60 v100 h-440 v-40')
            .on('click', function(d){
                const x = d3.mouse(this)[0];
                const yUP = x/(440/-60);
                const score = x/4.38;
                console.log(score);

                // Changed to 'self'
                self.setState({
                    score: score
                })
                d3.event.this.setAttribute('d',`M0,0 l${x},${yUP} v${yUP+40} h${-x} v-40`);
                d3.event.this.setAttribute('fill','forestgreen');
            }) 

    }

答案 1 :(得分:1)

如您所知,当您深入研究某些Javascript函数时,this的含义可能会改变。但是,该函数保留对其上方作用域变量的访问。因此,您可以创建一个临时变量,其中包含this的值,然后像这样在函数的 inside 中引用它:

renderInnerGauge = () => {
    const self = this;
    const innerGuage = this.svg.doAllTheThings('foo').on('click', function(d) {
        console.log('self', self); // this is the value of the "outer" this 
    });
}