【问题标题】:attrTween typescript issueattrTween 打字稿问题
【发布时间】:2019-01-10 00:27:47
【问题描述】:

我正在按照 d3 教程进行调整以适应打字稿并做出反应,但我遇到了 attrTween 的问题

selection
        .selectAll("rect")
        .data(this.state.data)
        .attr("x", d => this.x(d.name)!)
        .attr("height", 0)
        .attr("y", this.graphHeight)
        .attr("width", this.x.bandwidth())
        .attr("fill", "orange")
        // .merge(selection.selectAll("rects"))
        .transition()
        .attrTween("width", this.widthTween)
        .duration(500)
        .ease(easeLinear)
        .attr("y", d => this.y(d.orders))
        .attr("height", d => this.graphHeight - this.y(d.orders));

.attrTween("width", this.widthTween)

我得到一个类型 '(t:number) => number' 不能分配给类型 '(t:number) => string'

这里是widthTween函数

widthTween = () => {
    let i = interpolate(0, this.x.bandwidth());

    return (t: number) => {
        return i(t);
    };
};

【问题讨论】:

  • 为什么不把它作为 TypeScript 想要的字符串返回呢? return i(t) + ''; 无论如何,它最终都会在 DOM 中作为字符串结束。
  • 如果你将 width 初始化为 0 并将其转换为 this.x.bandwidth(),则不需要 attrTween
  • 是的,我知道,但这就是教程提供的内容,我只是跟着做,这也是对弧线的介绍
  • 您应该接受@Mark 的建议并将返回值转换为字符串。类型定义要求值是字符串,因为这正是 API 文档中为 .attrTween() 指定的内容:“插值器必须返回字符串。”.
  • 这正是我所做的。谢谢马克!知道如何投票或标记为答案:p

标签: reactjs typescript d3.js


【解决方案1】:

我遇到了同样的问题,但正如人们所说,你应该强制补间函数返回一个字符串,你可以在 attrTween 方法的重载中看到:

attrTween(name: string, factory: ValueFn<GElement, Datum, (t: number) => string>): this;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-09
    • 2015-12-17
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    相关资源
    最近更新 更多