首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用responsiveness响应pdf响应,但是当增加或减小窗口大小时,我得到了这个TypeError

使用responsiveness响应pdf响应,但是当增加或减小窗口大小时,我得到了这个TypeError
EN

Stack Overflow用户
提问于 2020-09-08 16:29:53
回答 1查看 3.5K关注 0票数 1
代码语言:javascript
复制
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:无法读取属性'getBoundingClientRect‘的null。10 _(_(_

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-08 16:46:19

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

请参阅useRef文档:

useRef返回一个可变的ref对象,该对象的.current属性初始化为传递的参数(initialValue)。返回的对象将持续到组件的整个生存期。

我将努力做到以下几点:

代码语言:javascript
复制
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));
  };
}, []);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63798025

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档