温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - ReactJS changing class to functional code
reactjs

其他 - ReactJS将类更改为功能代码

发布于 2020-03-27 11:55:07

我正在通过下面的代码:

class Canvas extends React.Component {
  componentDidMount() {
    const canvas = this.refs.canvas;
    const ctx = canvas.getContext("2d");
    const img = this.refs.image;

    img.onload = () => {
      ctx.drawImage(img, 0, 0);
      ctx.font = "40px Courier";
      ctx.fillText(this.props.text, 210, 75); // THIS IS THE PLACE TEXT IS EMBEDDED INTO THE PICTURE
    };
  }
  render() {
    return (
      <div>
        <canvas ref="canvas" width={640} height={425} />
        <img
          ref="image"
          alt="Stackoverflow56203352"
          src={backImg}
          className="hidden"
        />
      </div>
    );
  }
}

我正在尝试将其转换为功能形式,由于缺少的替换,到目前为止,我的工作一直停滞不前getContext

即我在这里尝试:

const Canvas = ({}) => {
  const canvas = useRef("")
  const ctx = canvas.getContext("2d")
  const img = useRef("")

  img.onload = () => {
    ctx.drawImage(img, 0, 0);
    ctx.font = "40px Courier";
    ctx.fillText(this.props.text, 210, 75); // THIS IS THE PLACE TEXT IS EMBEDDED INTO THE PICTURE
  };  

  return (
          <div>
            <canvas ref="canvas" width={640} height={425} />
            <img
              ref="image"
              alt="Stackoverflow56203352"
              src={backImg}
              className="hidden"
            />
          </div>
        );

}

没有削减。

完整的沙箱代码位于此位置

查看更多

查看更多

提问者
Zanam
被浏览
17
Will Jenkins 2019-07-04 01:06

主要变化是您需要进行布线useEffect,确保使用.current来访问画布和图像的当前参考。

最初,我认为它只能与单个文件一起使用,useEffect但是在重新加载页面时却失败了(我认为是由于图像被缓存并且没有onload再次触发)。加一秒钟useEffect就解决了(感谢Dennis Vash的帮助):

const Canvas = props => {
  const canvas = useRef(null);

  const image = useRef(null);

  useEffect(() => {
    const ctx = canvas.current.getContext("2d");
    image.current.onload = () => {
      ctx.drawImage(image.current, 0, 0);
      ctx.font = "40px Courier";
      ctx.fillText(props.text, 210, 75);
    };
  }, []);

  useEffect(() => {
    const ctx = canvas.current.getContext("2d");
    ctx.drawImage(image.current, 0, 0);
    ctx.font = "40px Courier";
    ctx.fillText(props.text, 210, 75);
  });

  return (
    <div>
      <canvas ref={canvas} width={640} height={425} />
      <img
        ref={image}
        alt="Stackoverflow56203352"
        src={backImg}
        className="hidden"
      />
    </div>
  );
};

另外,{}在您的参考资料(而不是引号)周围使用

在这里使用两个useRef钩子更新了沙箱