如何将D3 JavaScript中的'this'翻译成TypeScript? [英] How to translate 'this' in D3 JavaScript to TypeScript?

查看:294
本文介绍了如何将D3 JavaScript中的'this'翻译成TypeScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道JavaScript中的'this'与TypeScript中的含义不同,根据本文'this'。我在JavaScript中使用以下代码在所选节点上创建一个较粗的笔划,并为所有其他节点提供较小的笔划。

I know that 'this' in JavaScript has a different meaning than in in TypeScript, as per this article 'this' in TypeScript. I have the following code in JavaScript used to create a thicker stroke on the selected node, and give all other nodes a smaller stroke.

node.on('click', function (d) {
   d3.selectAll('circle').attr('stroke-width', 1.5);
   d3.select(this).select('circle').attr('stroke-width', 5);
})

在TypeScript中我有

In TypeScript I have

this.node.on('click', (d:any) => {
   this.node.selectAll('circle').attr('stroke-width', 1.5);
   [this is where I need help].select('circle').attr('stroke-width', 5);
}


推荐答案

正如此评论中所述此答案执行 not 在JavaScript和TypeScript之间有不同的含义。

As already stated in this comment and this answer, this does not have a different meaning between JavaScript and TypeScript.

话虽这么说,你的问题更平淡无奇:你正在尝试使用这个在箭头函数中获取当前的DOM元素,这根本不起作用。

That being said, your problem here is way more prosaic: you're trying to use this in an arrow function to get the current DOM element, and that will simply not work.

所以,简而言之,这里的问题是箭头函数和常规函数之间这个的区别,而不是在TypeScript和JavaScript之间。

So, in a nutshell, the problem here is the difference of this between an arrow function and a regular function, not between TypeScript and JavaScript.

解决方案

还有一个替代方案,在API中随处可见:当您在大多数D3方法中使用匿名函数时,传递的参数是......

There is an alternative to this, described everywhere in the API: when you use an anonymous function in most of D3 methods, the arguments being passed are...


...当前数据(d),当前索引(i)和当前组(节点), this 作为当前DOM元素(nodes [i])。

... the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]).

因此,这个只是节点组的当前索引(第二个参数)(第三个参数)。

Thus, this is simply the current index (the second argument) of the nodes groups (the third argument).

因此,在下面的代码段中:

So, in the snippet below:

selection.on("foo", function (d, i, n){
    console.log(this)
    console.log(n[i])
})

两个 console.log 将返回同样的事情。

The two console.log will return the same thing.

当您使用箭头功能时,解决方案是(在JavaScript中):

As you are using an arrow function, the solution is (in JavaScript):

this.nodes.on("click", (d, i, n) => {
    d3.select(n[i])//rest of your code here
})

如果你想了解更多关于使用第二个和第三个参数来获取DOM元素,请看这个例子:当'this`不可用时,d3 v4从拖动回调中检索拖动DOM目标

If you want to read more about the use of the second and the third arguments to get the DOM element, have a look at this example: d3 v4 retrieve drag DOM target from drag callback when `this` is not available

这篇关于如何将D3 JavaScript中的'this'翻译成TypeScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆