首页 > 解决方案 > 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(); 
        }

    }      

标签: reactjstypescriptcanvasreact-hooksuse-effect

解决方案


这是因为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

推荐阅读