我正在尝试创建一个集成了 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
on this
。
通常我可以使用箭头函数定义来解决这个问题,但是据我所知,为了在仪表中获取x
和y
使用值d3.mouse(this)
,我不能使用箭头函数。对于这种情况,有没有办法指向this
反应组件并在同一函数中使用鼠标方法?
如您所知,当您深入研究某些 Javascript 函数时, 的含义this
可能会改变。但是,该函数保持对其范围内的变量的访问。因此,您可以创建一个临时变量来保存 的值,this
然后从您的函数内部引用它,如下所示:
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
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句