gpt4 book ai didi

flowtype - Canvas 元素的正确类型

转载 作者:行者123 更新时间:2023-12-05 05:21:06 24 4
gpt4 key购买 nike

我正在尝试找出 Canvas 元素的正确类型。无论我做什么 - 它都不起作用。我已经尝试了所有可能的 html 元素类型,但 flow 说它们不兼容。那么为什么我不能将 canvas 元素分配给 HTMLCanvasElement 变量呢?

有什么想法吗?

节点参数是一个包含canvas元素的div元素。真的很简单。如果我剥离类型,一切正常。

export class Graph extends Component {
draw = (node: HTMLDivElement) => {
let canvas: HTMLCanvasElement = node.firstChild
if (canvas){
canvas.width = parseInt(getComputedStyle(node).getPropertyValue('width'))
canvas.height = parseInt(getComputedStyle(node).getPropertyValue('height'))
}
let chart = new Chart(canvas, {
type: this.props.type,
data: this.props.data
})
}
render = () => (
<div ref={this.draw} className='graph'>
<canvas />
</div>
)
}

我从 flow linter 得到这些错误:

Node This type is incompatible with HTMLCanvasElement
null This type is incompatible with HTMLCanvasElement
undefined This type is incompatible with HTMLCanvasElement

谢谢

附言它是 Inferno - 而不是 React。所以 ref 是一个函数,而不是一个字符串。只是为了避免人们纠正这一点。

最佳答案

看起来 HTMLDivElement 没有在 Flow 内部定义: https://github.com/facebook/flow/blob/v0.43.1/lib/dom.js#L2811

HTMLDivElementHTMLCanvasElement 是兄弟类型(都是 HTMLElement 的 child ),所以 Flow 自然会说尝试转换 是不安全的>HTMLDivElementHTMLCanvasElement 因为您通常不想在任何类型化系统中执行此操作。

您可以击败 Flow 的类型系统并通过将 node.firstChild 转换为 any 来解决这个问题。通常不推荐这样做,但在这种情况下似乎可以接受,因为 HTMLDivElement 不会给您任何东西,而您肯定知道它是什么。

let canvas: HTMLCanvasElement = (node.firstChild: any)

feel free to also view the flowtype.org/try link

关于flowtype - Canvas 元素的正确类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43367890/

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