【问题标题】:Error: Type "SVGAnimatedLength' has no call signatures" when calling from class错误:从类调用时,类型“SVGAnimatedLength'没有调用签名”
【发布时间】:2021-04-23 13:26:57
【问题描述】:

我正在使用 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.x() 上的 this 的类型为 SVGRectElement

【问题讨论】:

    标签: javascript typescript d3.js


    【解决方案1】:

    这是一个很好的例子,说明何时实际使用arrow functions 来支持常规函数!因为常规函数(例如在您的代码中)建立了自己的 this 范围,所以您不再能够访问您感兴趣的 this 范围,即您的周围类的范围。

    许多 D3 方法在 this 设置为当前 DOM 元素的情况下调用:

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

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

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

    【讨论】:

      【解决方案2】:

      this 具有 SVGRectElement 类型,因为它位于常规匿名函数中。在 D3 中,用于操作节点的方法将 this 上下文替换为正在被操作的自己的 DOM 元素,在您的情况下为 &lt;rect&gt;&lt;rect&gt; 节点没有 x 或 y 方法,因此会出现类型错误。

      将匿名函数替换为箭头函数preserves the this from the outside

      .attr('x', (d: HeatmapData) => {
                return this.x(d.dayNumber)
       })
       .attr('y', (d: HeatmapData) => {
                return this.y(d.timeOfDay)
       })
      

      现在,函数内部的this 与外部的this 相同,在您的例子中是包含svg、x、xAxis、y 和yAxis 的类。

      【讨论】:

        猜你喜欢
        • 2020-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多