首页 > 解决方案 > 错误:从类调用时,类型“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', ...)

thisat的this.x()类型为SVGRectElement.

标签: javascripttypescriptd3.js

解决方案


这是一个很好的例子,说明何时实际使用箭头函数来支持常规函数!因为常规函数——比如在你的代码中——建立了它们自己的this范围,所以你不再可以访问this你感兴趣的范围,即你周围类的范围。

许多 D3 方法在调用时this设置为当前 DOM 元素:

this作为当前 DOM 元素(节点[ i ])

为了能够通过引用它们来使用你的类实例的方法,this你可以只使用一个箭头函数,它没有自己的范围,但捕获其周围上下文的范围,即你的类/实例。因此,您的方法应如下所示:

.attr('x', d => this.x(d.dayNumber))

推荐阅读