如何将 d3 的每个方法与 ES6 箭头表示法一起使用

How to use d3's each method with ES6 arrow notation

本文关键字:表示 一起 ES6 d3 方法      更新时间:2023-09-26

出于某种原因,d3 使用this来引用.each()迭代中的当前元素。

我有这个代码:

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)使其正常工作?

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

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

试试这个

d3.selectAll(".region").each((data, index, nodes) => {
    d3.select(nodes[index]).style("fill", this.compute_color(...));
});