使用React Hooks响应pdf响应,但是当增加或减小窗口大小时,我会收到此TypeError

问题描述

import React,{ useState,useRef,useEffect } from 'react';
import throttle from 'lodash/throttle';
import { Document,Page } from 'react-pdf/dist/esm/entry.webpack';
import 'react-pdf/dist/esm/Page/AnnotationLayer.css';

export default function PDFWrapper({ data,onDocumentLoadSuccess,pageNumber }) {
  const [initialWidth,setinitialWidth] = useState(null);
  const pdfWrapper = useRef();

  const setPdfSize = () => {
    setinitialWidth(pdfWrapper.current.getBoundingClientRect().width);
  };

  useEffect(() => {
    window.addEventListener('resize',throttle(setPdfSize,3000));
    setPdfSize();
    return () => {
      window.removeEventListener('resize',3000));
    };
  });

  return (
    <div
      id="row"
      style={{
        height: '100vh',display: 'flex',}}
    >
      <div id="placeholderWrapper" style={{ height: '100vh' }} />
      <div id="pdfWrapper" style={{ width: '90vw' }} ref={pdfWrapper}>
        <Document
          file={data}
          onLoadSuccess={onDocumentLoadSuccess}
          noData=""
          loading=""
        >
          <Page pageNumber={pageNumber} loading="" width={initialWidth} />
        </Document>
      </div>
    </div>
  );
}

我将在此处复制整个错误。看来它来自setPdfSize函数。 注意:

TypeError:无法读取null的属性“ getBoundingClientRect”。 10 | const setPdfSize =()=> { 11 | setinitialWidth(pdfWrapper.current.getBoundingClientRect()。width); | ^ 12 | }; 13 | 14 | useEffect(()=> { 任何帮助将不胜感激。

解决方法

首先,我将在[]钩子中添加一个useEffect空的依赖项数组,以便仅在组件安装后才运行,可能您不想在同一事件中多次附加和分离。另外,我会在null函数中检查setPdfSize的值,因为它最初是null

请参见useRef文档:

useRef返回一个可变的ref对象,该对象的.current属性被初始化为传递的参数(initialValue)。返回的对象将在组件的整个生命周期中保持不变。

我将尝试以下操作:

const pdfWrapper = useRef(null);

const setPdfSize = () => {
  if (pdfWrapper && pdfWrapper.current) {
    setInitialWidth(pdfWrapper.current.getBoundingClientRect().width);
  }
};

useEffect(() => {
  window.addEventListener('resize',throttle(setPdfSize,3000));
  setPdfSize();
  return () => {
    window.removeEventListener('resize',3000));
  };
},[]);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...