【问题标题】:How to convert a React Class Component to a Function Component如何将 React 类组件转换为函数组件
【发布时间】:2020-02-01 10:02:20
【问题描述】:

我想在画布内显示图像。我将其作为类组件进行,但我的要求是使用函数组件:

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, this.props.data.w, this.props.data.h);
    }
  }  

  render() {
    const prop = this.props.data;
    return (
      <div data-id={prop.ukey} key={prop.ukey}>
        <canvas data-id={prop.ukey} key={prop.ukey} ref="canvas" width={prop.w} height={prop.h} />
        <img alt="doc-img" ref="image" src={prop.image} className="hidden" />
      </div>
    );
  }
}

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    由于您只需要在 componentDidMount 中执行代码,因此具有空依赖数组的 useEffect 与此等价。对于裁判,你也可以使用useRef hook

    const Canvas = ({data: prop}) => {
        const img = useRef(null);
        const cnv = useRef(null);
        useEffect(() => {
          const canvas = cnv.current;
          const image = img.current;
          const ctx = canvas.getContext("2d");  
    
          image.onload = () => {
            ctx.drawImage(image, 0, 0, prop.w, prop.h);
          }
        }, [])
        return (
          <div data-id={prop.ukey} key={prop.ukey}>
            <canvas data-id={prop.ukey} key={prop.ukey} ref={cnv} width={prop.w} height={prop.h} />
            <img alt="doc-img" ref={img} src={prop.image} className="hidden" />
          </div>
        );
    }
    

    附注我强烈建议您通过docs of hooks 并在将来尝试您的代码,然后再提出此类问题

    【讨论】:

    • 感谢 Shubham,在 const img = img.current; 上的“ReferenceError: Cannot access 'img' before initialization”之后出现错误;
    • 是的,正如你在上面的解决方案中提到的
    • 是的,现在正在工作。只需要在 const ctx = cnv.getContext("2d"); 处将cnv改为canvas;
    猜你喜欢
    • 2021-11-24
    • 2022-01-17
    • 2020-01-02
    • 2017-09-27
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    相关资源
    最近更新 更多