0

我怎样才能防止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>

</>
4

1 回答 1

0

分配ref给 DOM 元素的正确方法useRef

<canvas ref={canvasRef} />

文档:https ://reactjs.org/docs/hooks-reference.html#useref

https://codesandbox.io/s/gracious-cori-dj5nk?file=/src/App.js

于 2021-01-13T09:14:25.127 回答