gpt4 book ai didi

javascript - 使用 d3.mouse : 'this' implicitly has type 'any' because it does not have a type annotation 时出现 D3 Typescript 错误

转载 作者:行者123 更新时间:2023-11-30 19:07:55 28 4
gpt4 key购买 nike

我在我的 React 应用程序中使用 d3,我在其中使用 Typescript 编写代码。我有以下代码:

function mousemove() {
// recover coordinate we need
var x0 = xScale.invert(d3.mouse(this)[0]);
var i = bisect(data, x0, 1);
var selectedData = data[i]
focus
.attr("cx", xScale(selectedData.dateCreated))
.attr("cy", yScale(selectedData[value]))
focusText
.html("x:" + selectedData.x + " - " + "y:" + selectedData.y)
.attr("x", xScale(selectedData.dateCreated) + 15)
.attr("y", yScale(selectedData[value]))
}

d3.mouse(this)[0] 抛出以下错误:

'this' implicitly has type 'any' because it does not have a type annotation.

有什么建议可以解决吗?这个错误是常见的 typescript ,但我不知道如何用 d3.mouse 函数解决它。

最佳答案

我假设这是传递给 d3.js 事件处理程序的自定义方法(即 .on('mousemove'))

您可以通过引用实际的事件处理程序来处理事件回调,而不是引用可能被推断为当前类的实例的 this

.on('mousemove' (d, i) => {
mousemove();
})

function mousemove() {
const x0 = xScale.invert(d3.mouse(d3.event.currentTarget));
// do the rest
}

或者,您可以将节点传递给您的 mousemove() 函数。根据documentation ,

If the selector is a function, it is evaluated for each selected element, in order, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]).

.on('mousemove' (d, i, n) => {
const node = d[i]
mousemove(node);
})

function mousemove(node) {
// do the rest
}

关于javascript - 使用 d3.mouse : 'this' implicitly has type 'any' because it does not have a type annotation 时出现 D3 Typescript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58788554/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com