[英]React useRef / useEffect HTMLCanvasElement not assignable
I am fairly new to React and struggling to get a JS object to render through useRef and useEffect.我对 React 相当陌生,并且努力让 JS object 通过 useRef 和 useEffect 呈现。
The JS render method is as follows: JS渲染方法如下:
import { Compass } from "steelseries";
const compass = new Compass(document.querySelector("#myCanvas"), {
size: 200
});
Using a template for rendering a chart from chart.js I have tried to render this through React with typescript.使用模板从 chart.js 渲染图表,我尝试通过 React 与 typescript 渲染它。
The react render method is as follows: react渲染方法如下:
import { useCallback, useEffect, useRef } from "react"
import { observer } from "mobx-react"
import { Compass } from "steelseries"
type GaugeIndicatorProps = {
value: 200
}
export const Gauge = observer(({ value }: GaugeIndicatorProps) => {
const canvasEl = useRef() as React.MutableRefObject<HTMLCanvasElement>
const chartRef = useRef<Compass | null>()
const createChart = useCallback(() => {
const chartCanvas = canvasEl.current.getContext("2d")
if (!chartCanvas) {
return
}
chartRef.current = new Compass(chartCanvas, value)
}, [value])
useEffect(() => {
if (!chartRef.current) {
createChart()
}
}, [createChart])
return (
<div className={`canvas`}>
<canvas className="top-chart" ref={canvasEl} />
</div>
)
})
Not sure how to get this to render, because the compass object wants a Canvas |不知道如何渲染,因为指南针 object 想要 Canvas | String |字符串 | HTMLCanvasElement, which i have tried to pass to it using React.MutableRefObject and a getcontext("2d"), yet it is saying the following error for chartCanvas on this line of Code: chartRef.current = new Compass(chartCanvas, value) HTMLCanvasElement,我曾尝试使用 React.MutableRefObject 和 getcontext("2d") 将其传递给它,但它在这行代码中对 chartCanvas 表示以下错误: chartRef.current = new Compass(chartCanvas, value)
Argument of type 'CanvasRenderingContext2D' is not assignable to parameter of type 'string | 'CanvasRenderingContext2D' 类型的参数不能分配给'string | 类型的参数HTMLCanvasElement'. HTMLCanvas 元素”。 Type 'CanvasRenderingContext2D' is missing the following properties from type 'HTMLCanvasElement': hieght etc “CanvasRenderingContext2D”类型缺少“HTMLCanvasElement”类型的以下属性:hieght 等
Sorry if this is a newbie question.对不起,如果这是一个新手问题。
Thanks for your support.谢谢你的支持。
Christopher克里斯托弗
You have to pass the canvas itself, not its context.您必须通过 canvas 本身,而不是其上下文。 Use:利用:
chartRef.current = new Compass(canvasEl.current, value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.