Dav*_*uce 3 canvas typescript reactjs react-hooks use-effect
我试图使用 React hooks 和 Typescript 创建一个具有一些基本形状的画布元素,但我遇到了一个错误,其中 useEffect() 中的上下文可能为 null (ts2531)。
我假设这是因为我的 canvasRef 默认为 null,但我有点不确定我还可以将其设置为什么,或者是否有更好的方法来解决这个问题?
这是到目前为止我的代码(编辑,解决方案如下):
import React, { useRef, useEffect } from 'react';
interface CanvasProps {
width: number;
height: number;
}
const Canvas = ({ width, height }: CanvasProps) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
if (canvasRef.current) {
const canvas = canvasRef.current;
const context = canvas.getContext('2d');
context.beginPath();
+ context.arc(50, 50, 50, 0, 2 * Math.PI);
+ context.fill();
}
},[]);
return <canvas ref={canvasRef} height={height} width={width} />;
};
Canvas.defaultProps = {
width: window.innerWidth,
height: window.innerHeight
};
export default Canvas;
Run Code Online (Sandbox Code Playgroud)
在 Alex Wayne 的快速回答之后,这是我更新的 useEffect(),它有效。
useEffect(() => {
if (canvasRef.current) {
const canvas = canvasRef.current;
const context = canvas.getContext('2d');
if (context) {
context.beginPath();
context.arc(50, 50, 50, 0, 2 * Math.PI);
context.fill();
}
}
Run Code Online (Sandbox Code Playgroud)
这是因为getContext
可以返回null
。文档:https ://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext
如果 contextType 与可能的绘图上下文不匹配,则返回 null。
确保它不是null
例如
const context = canvas.getContext('2d');
if (context == null) throw new Error('Could not get context');
// now safe
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
17067 次 |
最近记录: |