我正在尝试找出 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
HTMLDivElement
和 HTMLCanvasElement
是兄弟类型(都是 HTMLElement
的 child ),所以 Flow 自然会说尝试转换 是不安全的>HTMLDivElement
到 HTMLCanvasElement
因为您通常不想在任何类型化系统中执行此操作。
您可以击败 Flow 的类型系统并通过将 node.firstChild
转换为 any
来解决这个问题。通常不推荐这样做,但在这种情况下似乎可以接受,因为 HTMLDivElement
不会给您任何东西,而您肯定知道它是什么。
let canvas: HTMLCanvasElement = (node.firstChild: any)
关于flowtype - Canvas 元素的正确类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43367890/