[英]How to use d3's each method with ES6 arrow notation
For some reason, d3 uses this
to refer to the current element in a .each()
iteration.出于某种原因,d3 使用this
来引用.each()
迭代中的当前元素。
I had this code:我有这个代码:
var me = this;
...
d3.selectAll(".region").each(function(d) {
d3.select(this).style("fill", me.compute_color(...));
})
With ES6, I can use the arrow notation to avoid overwriting this
:使用 ES6,我可以使用箭头符号来避免覆盖this
:
d3.selectAll(".region").each(d => {
d3.select(this).style("fill", this.compute_color(...));
})
However, this code doesn't work because d3 is selecting the wrong element.但是,此代码不起作用,因为 d3 选择了错误的元素。 In fact, I have lost the only reference to the element, because this
was not overridden by d3.事实上,我已经丢失了对元素的唯一引用,因为this
没有被 d3 覆盖。
How can I change d3.select(this)
so that it works?如何更改d3.select(this)
以使其正常工作?
You can use the index that is passed as second argument to access the right element from the collection: 您可以使用作为第二个参数传递的索引来访问集合中的正确元素:
let selection = d3.selectAll(".region");
selection.each((d, i) => {
d3.select(selection[0][i]).style("fill", this.compute_color(...));
})
You can try this你可以试试这个
d3.selectAll(".region").each((data, index, nodes) => {
d3.select(nodes[index]).style("fill", this.compute_color(...));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.