H. *_*llo 5 javascript lexical-scope d3.js typescript arrow-functions
我知道JavaScript中的'this'与TypeScript中的含义不同,根据TypeScript中的这篇文章'this'.我在JavaScript中使用以下代码用于在所选节点上创建较粗的笔划,并为所有其他节点提供较小的笔划.
node.on('click', function (d) {
d3.selectAll('circle').attr('stroke-width', 1.5);
d3.select(this).select('circle').attr('stroke-width', 5);
})
Run Code Online (Sandbox Code Playgroud)
在TypeScript我有
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);
}
Run Code Online (Sandbox Code Playgroud)
Ger*_*ado 10
正如已经指出此评论和这个答案,this也不能有JavaScript和打字稿之间有不同的含义.
话虽这么说,你的问题在这里更平淡:你试图this在箭头函数中使用来获取当前的DOM元素,而这根本行不通.
因此,简而言之,这里的问题是this箭头函数和常规函数之间的区别,而不是TypeScript和JavaScript之间的区别.
解
this在API中的任何地方都有一个替代方案:在大多数D3方法中使用匿名函数时,传递的参数是......
...当前数据(d),当前索引(i)和当前组(节点),以及
this当前DOM元素(nodes [i]).
因此, this它只是节点组的当前索引(第二个参数)(第三个参数).
所以,在下面的代码段中:
selection.on("foo", function (d, i, n){
console.log(this)
console.log(n[i])
})
Run Code Online (Sandbox Code Playgroud)
两者console.log将返回相同的东西.
当您使用箭头功能时,解决方案是(在JavaScript中):
this.nodes.on("click", (d, i, n) => {
d3.select(n[i])//rest of your code here
})
Run Code Online (Sandbox Code Playgroud)
如果你想了解更多关于使用第二个和第三个参数来获取DOM元素的信息,请看一下这个例子:d3 v4当`this`不可用时从drag回调中检索拖动DOM目标
H. *_*llo -2
答案是将“this”替换为“d3.event.currentTarget”
d3.select(d3.event.currentTarget).select('circle').attr('stroke-width', 5);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1267 次 |
| 最近记录: |