使用 React Hooks 反应 pdf 响应能力,但是当增加或减少 window 大小时我得到这个 TypeError

React pdf responsiveness using React Hooks, but when increasing or decreasing window size I get this 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', throttle(setPdfSize, 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: Cannot read property 'getBoundingClientRect' of null. 10 | const setPdfSize = () => { 11 | setInitialWidth(pdfWrapper.current.getBoundingClientRect().width); | ^ 12 | }; 13 | 14 | useEffect(() => { Any help will be appreciated.

首先,我会添加 [] 一个空的依赖数组到 useEffect 挂钩,以便 运行 只有在安装组件后,可能你不想附加和分离同一事件多次。我还会检查 setPdfSize 函数中的 null 值,因为它最初是 null.

参见 useRef 文档:

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

我会尝试如下:

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', throttle(setPdfSize, 3000));
  };
}, []);