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

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

问题描述

根据这篇文章,我知道 JavaScript 中的this"与 TypeScript 中的含义不同 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);
}

推荐答案

此评论此答案this 在 JavaScript 和 TypeScript 之间没有具有不同的含义.

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

话虽如此,但您的问题更加平淡无奇:您试图在箭头函数中使用 this 来获取当前的 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.

所以,简而言之,这里的问题是 this 在箭头函数和常规函数之间的区别,而不是 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.

解决方案

this 有一个替代方法,在 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元素(节点[i]).

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

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

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 元素的信息,请查看此示例:d3 v4 在 `this` 不可用时从拖动回调中检索拖动 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天全站免登陆