【问题标题】:ReactJS changing class to functional codeReactJS 将类更改为功能代码
【发布时间】:2019-07-03 15:25:56
【问题描述】:

我正在处理以下代码:

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

}

不会剪掉它。

完整的沙盒代码在location

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    主要变化是您需要在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 钩子 here 更新了沙盒

    【讨论】:

    • 尝试刷新页面几次
    • 使用您的代码图像上的文字消失。我在问题中给出了一个沙盒链接。
    • 已更新...理想情况下,渲染代码应该移到单独的 useCallback 中,但它现在可以工作了。
    • 我将字体渲染重新添加到第一个 useEffect 的“onload”中,并从第二个中删除了 props.text 依赖限制。
    • 谢谢!!很大的帮助
    猜你喜欢
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 2012-03-13
    • 2021-09-16
    • 1970-01-01
    相关资源
    最近更新 更多