Jam*_*mes 9 reactjs react-hooks
我想我可能在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>
);
}
Run Code Online (Sandbox Code Playgroud)
第一次尝试访问时ctx.current,它仍然未定义,因为此效果中的赋值仍未发生:
useEffect(()=>{
ctx.current = canvasRef.current.getContext('2d')
},[])
Run Code Online (Sandbox Code Playgroud)
这是因为效果是在渲染阶段之后运行的。
您需要在内部执行此操作useEffect:
useEffect(()=>{
ctx.current = canvasRef.current.getContext('2d')
ctx.current.fillStyle= "green"
ctx.current.fillRect(20,20,150,100)
},[])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19619 次 |
| 最近记录: |