javascript - 错误:从类调用时,类型“SVGAnimatedLength'没有调用签名”
问题描述
我正在使用 D3.js、TypeScript 和 Vue Property Decorator 开发 Vue 项目。我想绘制热图,但是当我想调用x()
或y()
函数以返回热图中每个单元格的计算位置时出现错误。它抛出错误
类型“SVGAnimatedLength”没有调用签名。
这就是我初始化图表变量的方式
private svg: d3.Selection<SVGGElement, any, HTMLElement, any>
private x: d3.ScaleBand<string>
private xAxis: d3.Selection<SVGGElement, any, HTMLElement, any>
private y: d3.ScaleBand<string>
private yAxis: d3.Selection<SVGGElement, any, HTMLElement, any>
这是导致错误的地方
this.svg.selectAll()
.data(this.getData().filter((datum: HeatmapData) => this.betweenTwoDates(datum)))
.enter()
.append('rect')
.attr('x', function(d: HeatmapData) {
return this.x(d.dayNumber)
})
.attr('y', function(d: HeatmapData) {
return this.y(d.timeOfDay)
})
.attr('cx', 1)
.attr('cy', 1)
.attr('width', this.x.bandwidth())
.attr('height', this.y.bandwidth())
在
.attr('x', function(d: HeatmapData) {
return this.x(d.dayNumber)
})
错误发生在return this.x(d.dayNumber)
说明Type "SVGAnimatedLength" has no call signatures
。也一样.attr('y', ...)
。
this
at的this.x()
类型为SVGRectElement
.
解决方案
这是一个很好的例子,说明何时实际使用箭头函数来支持常规函数!因为常规函数——比如在你的代码中——建立了它们自己的this
范围,所以你不再可以访问this
你感兴趣的范围,即你周围类的范围。
许多 D3 方法在调用时this
设置为当前 DOM 元素:
以this作为当前 DOM 元素(节点[ i ])
为了能够通过引用它们来使用你的类实例的方法,this
你可以只使用一个箭头函数,它没有自己的范围,但捕获其周围上下文的范围,即你的类/实例。因此,您的方法应如下所示:
.attr('x', d => this.x(d.dayNumber))
推荐阅读
- android - 从 Android 11 的旧位置迁移数据
- android - 如何进入荣耀10 Lite的自动启动权限页面?
- java - 面对 java.lang.ClassCastException:android.net.DhcpInfo 无法转换为 android.bluetooth.BluetoothDevice
- django-models - 字段“tag_number”需要一个数字,但得到“КР-02211”
- r - RStudio 冻结并且即使在重新安装后也无法工作
- sql - 将列添加到 SELECT 后,PostgreSQL 左连接变得非常慢
- windows - 如何在 windows 中安装和运行 Tor 服务?(Windows v.10)
- php - Laravel 从带有偏移量的集合中获取
- r - 对数据框的值进行操作
- jenkins - 部署了 .net core web api,无法使用节点端口通过 kubernetes 集群访问应用程序