我想我可能在useRef
这里滥用了。当我尝试画到画布上,我得到以下错误:cannot set 'fillStyle' of undefined
。
import React, { useEffect, useRef } from "react";
import useWindowSize from "../hooks/useWindowSize";
export default function Player() {
const canvasRef = useRef();
const ctx = useRef();
useEffect(() => {
ctx.current = canvasRef.current.getContext("2d");
}, []);
ctx.current.fillStyle = "green";
ctx.current.fillRect(20, 20, 150, 100);
return (
<React.Fragment>
<div>Hello</div>
<canvas ref={canvasRef} width="500" height="500" />
</React.Fragment>
);
}