ref undefined в модальном компоненте ui материала

Как я могу сделать так, чтобы 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>

</>

person Jayg713    schedule 13.01.2021    source источник
comment
Привет, ты видел мой ответ?   -  person Mosh Feu    schedule 27.01.2021


Ответы (1)


Правильный способ присвоить 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

person Mosh Feu    schedule 13.01.2021