我正在尝试创建一个集成了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
获得y
和d3.mouse(this)
的值,我无法使用箭头功能。在这种情况下,是否可以将this
指向react组件并在同一函数中使用mouse方法?
答案 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
});
}