Javascript 如何将React类组件转换为函数组件

Javascript 如何将React类组件转换为函数组件,javascript,reactjs,react-hooks,Javascript,Reactjs,React Hooks,我想在画布中显示一个图像。我是作为类组件完成的,但我的要求是使用函数组件: class Canvas extends React.Component { componentDidMount() { const canvas = this.refs.canvas; const ctx = canvas.getContext("2d"); const img = this.refs.image; img.onload = () =&g

我想在画布中显示一个图像。我是作为类组件完成的,但我的要求是使用函数组件:

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>
    );
  }
}
类画布扩展React.Component{
componentDidMount(){
const canvas=this.refs.canvas;
const ctx=canvas.getContext(“2d”);
const img=this.refs.image;
img.onload=()=>{
drawImage(img,0,0,this.props.data.w,this.props.data.h);
}
}  
render(){
const prop=this.props.data;
返回(
);
}
}

因为您只需要在componentDidMount中执行代码,所以带有空依赖项数组的
useEffect
就相当于此。对于refs,您也可以使用
useRef
hook

constcanvas=({data:prop})=>{
常量img=useRef(null);
const cnv=useRef(空);
useffect(()=>{
const canvas=cnv.current;
常量图像=img.current;
const ctx=canvas.getContext(“2d”);
image.onload=()=>{
ctx.drawImage(图像,0,0,道具w,道具h);
}
}, [])
返回(
);
}

p.S.我强烈建议您在提出此类问题之前,仔细阅读并在将来尝试您的代码

谢谢Shubham,在const img=img.current上的“ReferenceError:初始化前无法访问'img'”之后,我收到了错误;是的,正如您在上述解决方案中所提到的,是的,正在工作。只需要在const ctx=cnv.getContext(“2d”)处将cnv更改为画布;