我怎样才能防止canvasRef.current
在这里未定义?似乎材料 ui 中的模态组件导致画布参考出现问题。我怎样才能防止这种情况发生?我通过设置节点值尝试了 ref 回调canvasRef.current
,但仍然没有运气。
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; // canvas.current is undefined here
const context = canvas.getContext('2d');
canvas.height = 650;
const renderContext = {
canvasContext: context,
};
page.render(renderContext);
});
});
}, []);
return (
<>
<Modal>
<canvas ref={(e) => {canvasRef.current = e}} />
</Modal>
<button onClick={handleViewStuff}>View stuff</button>
</>