用ref反应画布,省略调用ref.current和ctx?

时间:2019-08-16 20:26:00

标签: javascript reactjs canvas ref

是否可以省略呼叫

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

我每次想在功能或使用效果中引用canvas DOM节点吗?

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} />;
};

我无法将canvasRef.current设置为变量,因为它在第一次迭代时的值为空。

1 个答案:

答案 0 :(得分:1)

实际上,您不能将当前参考节点设置为变量。

如果必须在不同的组件中实现相同的逻辑,则可以创建自己的钩子:

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} />);
};

一些评论: