反应 useRef 未定义 [英] React useRef is undefined

查看:51
本文介绍了反应 useRef 未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我可能在这里误用了 useRef.当我尝试在画布上绘制时出现以下错误:cannot set 'fillStyle' of undefined.

I think I may be misusing useRef here. When I try to draw to the canvas I am getting the following error: 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>
  );
}

推荐答案

第一次尝试访问 ctx.current 时,仍然是 undefined 因为这个效果里面的赋值还是没有发生:

The first time you are trying to access ctx.current, it's still undefined because the assignment inside this effect still didn't happen:

useEffect(()=>{
    ctx.current = canvasRef.current.getContext('2d')
},[])

这是因为效果在渲染阶段之后运行.

This is because the effect is run after the rendering phase.

您需要在 useEffect 中执行此操作:

You need to do that inside useEffect instead:

useEffect(()=>{
    ctx.current = canvasRef.current.getContext('2d')
    ctx.current.fillStyle= "green"
    ctx.current.fillRect(20,20,150,100)
},[])

这篇关于反应 useRef 未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆