如何使用ES6箭头符号结合d3的each方法?

3

由于某些原因,d3在.each()迭代中使用this来引用当前元素。

我有这段代码:

var me = this;
...
d3.selectAll(".region").each(function(d) {
    d3.select(this).style("fill", me.compute_color(...));
})

在ES6中,我可以使用箭头符号来避免覆盖this

d3.selectAll(".region").each(d => {
    d3.select(this).style("fill", this.compute_color(...));
})

然而,这段代码无法正常工作,因为d3选择了错误的元素。实际上,我已经失去了对该元素唯一的引用,因为this没有被d3覆盖。

我该如何更改d3.select(this)以使其正常工作?


不太确定,但我认为你不能在不改变d3.each代码的情况下实现,因为箭头函数无法捕获由其代码(节点)发送的this。因此,对于这些情况,保持传统方式是最好的选择。 - juvian
问题是我已经从所有地方删除了旧的“我”... 我不想回滚一切。 - William
也许你可以自己迭代:d3.selectAll(".region")[0].forEach(d => { d3.select(d).style("fill", this.compute_color(...)); }) 但是这里的d将指向d3元素而不是数据。 - juvian
或者使用他们的each代码作为参考,制作自己的eachArrow函数:http://jsfiddle.net/pW4Te/64/ - juvian
2
在箭头函数中,无法使用自定义的 this,在创建时生效的 this 已经固定,就像闭包一样... - dandavis
2个回答

0

你可以使用作为第二个参数传递的索引来从集合中访问正确的元素:

let selection = d3.selectAll(".region");
selection.each((d, i) => {
    d3.select(selection[0][i]).style("fill", this.compute_color(...));
})

0
你可以试试这个。
d3.selectAll(".region").each((data, index, nodes) => {
    d3.select(nodes[index]).style("fill", this.compute_color(...));
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接