【问题标题】:ref undefined within a modal component material ui参考未定义在模态组件材料 ui 中
【发布时间】:2021-04-18 03:35:10
【问题描述】:

如何防止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>

</>

【问题讨论】:

  • 嗨,你看到我的回答了吗?

标签: reactjs material-ui use-ref


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 2020-08-06
    相关资源
    最近更新 更多