【问题标题】:REACT Uncaught TypeError: Cannot read property 'load' of nullREACT Uncaught TypeError:无法读取 null 的属性“加载”
【发布时间】:2020-01-18 20:02:57
【问题描述】:

这是iframe 加载器代码,它在类组件中运行良好 我尝试处理 iframe,所以 iframe 给我 null 但我需要处理 iframe。加载我怎么能得到它? 也许我需要更改加载器代码中的某些内容?

HTMLIFrameElement.prototype.load = function(url, callback) {
  const iframe = this;
  try {
    iframe.src =
      url +
      '?rnd=' +
      Math.random()
        .toString()
        .substring(2);
  } catch (err) {
    if (!callback) {
      return new Promise((resolve, reject) => {
        reject(err);
      });
    } else {
      callback(err);
    }
  }
  const maxTime = 60000;
  const interval = 200;

  let timerCount = 0;

  if (!callback) {
    return new Promise((resolve, reject) => {
      const timer = setInterval(() => {
        if (!iframe) return clearInterval(timer);
        timerCount++;
        if (
          iframe.contentDocument &&
          iframe.contentDocument.readyState === 'complete'
        ) {
          clearInterval(timer);
          resolve();
        } else if (timerCount * interval > maxTime) {
          reject(new Error('Iframe load failed'));
        }
      }, interval);
    });
  } else {
    const timer = setInterval(() => {
      if (!iframe) return clearInterval(timer);
      timerCount++;
      if (
        iframe.contentDocument &&
        iframe.contentDocument.readyState === 'complete'
      ) {
        clearInterval(timer);
        callback();
      } else if (timerCount * interval > maxTime) {
        callback(new Error('Iframe load failed'));
      }
    }, interval);
  }
};

可生产示例:https://codesandbox.io/s/winter-leaf-vgb6t

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    我不知道你在做什么,这个sn-p有很多错误,但是这里有一个如何获取iframe的引用的例子:

    import React, { useEffect, useRef } from 'react';
    import './helpers/iframeLoader.js';
    const currentPage = 'index.html';
    
    const Editor = () => {
      const iframeRef = useRef();
    
      useEffect(() => {
        iframeRef.current.load(currentPage, () => {
          const body = iframeRef.current.contentDocument.body;
          body.childNodes.forEach(node => {
            console.log(node);
          });
        });
      }, []);
    
      return (
        <iframe title="iframe" ref={iframeRef} src={currentPage} frameBorder="0" />
      );
    };
    
    export default Editor;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-20
      • 2014-05-04
      • 2019-11-21
      • 1970-01-01
      相关资源
      最近更新 更多