最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React canvas with ref omitting calling ref.current and ctx? - Stack Overflow

programmeradmin2浏览0评论

Is it possible to omit to call

const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');

each time I want to refer to canvas DOM node in a function or useEffect hook?

const drawCanvas = () => {
  const canvasRef = React.useRef(null);
  const [position, setPosition] = React.useState({});

  React.useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    ctx.fillRect(0, 0, canvas.width, canvas.height);
  }, []);

  React.useEffect(() => {
    const canvas = canvasRef.current;
    const x = canvas.width;
    const y = canvas.height;
    setPosition({ x, y });
  }, []);

  return <canvas ref={canvasRef} />;
};

Is it possible to omit to call

const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');

each time I want to refer to canvas DOM node in a function or useEffect hook?

const drawCanvas = () => {
  const canvasRef = React.useRef(null);
  const [position, setPosition] = React.useState({});

  React.useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    ctx.fillRect(0, 0, canvas.width, canvas.height);
  }, []);

  React.useEffect(() => {
    const canvas = canvasRef.current;
    const x = canvas.width;
    const y = canvas.height;
    setPosition({ x, y });
  }, []);

  return <canvas ref={canvasRef} />;
};

Share Improve this question edited Aug 29, 2020 at 20:17 Nalhin asked Aug 16, 2019 at 20:26 NalhinNalhin 4122 gold badges7 silver badges14 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

Indeed, you cannot set the current ref node to a variable.

If you have to implement the same logic in different ponents, you could create your own hook:

const useCanvas = (callback) => {
  const canvasRef = React.useRef(null);

  React.useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    callback([canvas, ctx]);
  }, []);

  return canvasRef;
}

const Canvas = () => {
  const [position, setPosition] = React.useState({});
  const canvasRef = useCanvas(([canvas, ctx]) => {
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    const x = canvas.width;
    const y = canvas.height;
    setPosition({ x, y });
  });

  return (<canvas ref={canvasRef} />);
};

A few remarks:

  • I renamed your drawCanvas function to Canvas - a more standard way to name your React function ponents
  • The above custom hook is suited for a simple use case where it runs only once after the initial render. Otherwise, you could run into a problem with this approach (see here for more details: https://medium./@teh_builder/ref-objects-inside-useeffect-hooks-eb7c15198780)
发布评论

评论列表(0)

  1. 暂无评论