Reactjs 反应类型脚本,无法使用上下文更改画布
画布以正确的大小渲染,但画布从不填充蓝色,我不明白为什么Reactjs 反应类型脚本,无法使用上下文更改画布,reactjs,typescript,canvas,Reactjs,Typescript,Canvas,画布以正确的大小渲染,但画布从不填充蓝色,我不明白为什么 import React, { useRef } from 'react'; const App = () => { console.log('this prints just fine'); const canvasWidth = 820; const canvasHeight = 620; const canvasRef = useRef<HTMLCanvasElement>(null); co
import React, { useRef } from 'react';
const App = () => {
console.log('this prints just fine');
const canvasWidth = 820;
const canvasHeight = 620;
const canvasRef = useRef<HTMLCanvasElement>(null);
console.log(canvasRef.current) // null
if (canvasRef.current) {
console.log('this never prints!!');
const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');
if (ctx) {
console.log('this never prints!!');
ctx.fillStyle = 'blue';
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
canvas.width = canvasWidth;
canvas.height = canvasHeight;
}
}
return (
<canvas
ref={canvasRef}
width={canvasWidth}
height={canvasHeight}
>
</canvas>
);
};
export { App };
import React,{useRef}来自“React”;
常量应用=()=>{
log(“这打印得很好”);
常量画布宽度=820;
常数画布高度=620;
const canvasRef=useRef(null);
console.log(canvasRef.current)//null
如果(canvasRef.current){
log('这永远不会打印!!');
const canvas=canvasRef.current;
const ctx=canvas.getContext('2d');
如果(ctx){
log('这永远不会打印!!');
ctx.fillStyle='蓝色';
ctx.fillRect(0,0,画布宽度,画布高度);
canvas.width=画布宽度;
canvas.height=画布高度;
}
}
返回(
);
};
导出{App};
更新
const App: React.FC = () => {
const canvasRef = useRef<HTMLCanvasElement>(null);
const canvasWidth = 820;
const canvasHeight = 620;
useEffect(() => {
...
const-App:React.FC=()=>{
const canvasRef=useRef(null);
常量画布宽度=820;
常数画布高度=620;
useffect(()=>{
...
上面解决了这个问题我认为您应该在componentDidMount或useEffect挂钩中进行上下文填充。由于在初始化组件时画布没有呈现,因此它的画布上下文必须为null或未定义。useEffect获得了它,谢谢!