尝试设置canvasRef.current时收到未定义的错误。我尝试了多种方法来形成回调ref,但是我没有走运。在canvasRef.current不是未定义的情况下,如何等待触发onClick函数'handleViewStuff'?
const Child = (props) => {
const canvasRef = useRef();
const handleViewStuff = useCallback(() => {
apiCall(id)
.then((response) => {
// do stuff
return stuff;
})
.then((result) => {
result.getPage().then((page) => {
const canvas = canvasRef.current;
const context = canvas.getContext('2d'); // error is coming in here as getContext of undefined meaning canvas is undefined'
canvas.height = 650;
const renderContext = {
canvasContext: context,
};
page.render(renderContext);
});
});
}, []);
return (
<Fragment>
<canvas ref={(e) => {canvasRef.current = e}} />
<Button
onClick={handleViewStuff}
>
View Stuff
</Button>
</Fragment>
);
};
export default Child;
if-statement
...
if(canvas.current) {
const canvas = canvasRef.current;
const context = canvas.getContext('2d');
}
optional chaining
...
const canvas = canvasRef?.current;
const context = canvas?.getContext('2d');
而且我在您的代码中发现了一些错误。
useCallback
const handleViewStuff = useCallback(() => {
...
}, [canvasRef.current]);
<canvas ref={canvasRef} />
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句