reactjs - HTML Canvas,带有 React 钩子和 Typescript
问题描述
我试图使用 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;
继亚历克斯韦恩的快速回答之后,这是我更新的 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();
}
}
解决方案
这是因为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
推荐阅读
- azure - 为什么“Microsoft.Web/sites”的“FileSystemUsage”指标总是返回零?
- javascript - React Native API 数据获取并保存为全局数据
- java - Kafka连接音频文件
- moodle - 具有固定和预先指定数量的正确和错误答案的问题
- php - Laravel - 从产品表中获取结果,我将结果与属性表匹配
- xamarin - 更新 Nuget 包后缺少 Xamarin 代码
- c# - 程序集 '' 引用程序集 'microsoft.sqlserver.dtsruntimewrap, ',它在当前数据库中不存在
- java - 如何使用流和 lambda 从 int[] 数组中打印和选择数字
- python - 查找文本文件中适合两种格式之一的所有字符串
- powerbi - Power BI如何根据日期切片器和过滤器显示列的最新值?