问题描述
如何防止 canvasRef.current
在此处未定义?材料 ui 中的模态组件似乎导致画布参考出现问题。我怎样才能防止这种情况发生?我通过将 canvasRef.current
设置为节点值来尝试 ref 回调,但仍然没有运气。
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>
</>
解决方法
使用 ref
将 useRef
分配给 DOM 元素的正确方法是
<canvas ref={canvasRef} />
文档:https://reactjs.org/docs/hooks-reference.html#useref
https://codesandbox.io/s/gracious-cori-dj5nk?file=/src/App.js