javascript - 如何设置react组件的iframe内容

标签 javascript iframe reactjs xmlhttprequest

我正在尝试在 React 组件中设置 iframe 的内容,但我无法做到这一点。我有一个组件,其中包含一个函数,当 iframe 完成加载时必须调用该函数。在该函数中,我正在设置内容,但似乎根本没有调用 onload 函数。我正在 Chrome 浏览器中测试它。我正在尝试以下操作:

var MyIframe = React.createClass({
    componentDidMount : function(){
        var iframe = this.refs.iframe.getDOMNode();
        if(iframe.attachEvent){
            iframe.attacheEvent("onload", this.props.onLoad);
        }else{
            iframe.onload = this.props.onLoad;
        }
    },
    render: function(){
        return <iframe ref="iframe" {...this.props}/>;
    }
});

var Display = React.createClass({
    getInitialState : function(){
        return {
            oasData : ""
        };
    },
    iframeOnLoad : function(){
        var iframe = this.refs.bannerIframe;
        iframe.contentDocument.open();
        iframe.contentDocument.write(['<head></head><style>body {margin: 0; overflow: hidden;display:inline-block;} html{ margin: 0 auto; text-align: center;} body > a > img {max-width: 100%; height: inherit;}', extraCss, '</style></head><body>', this.state.oasData.Ad[0].Text, '</body>'].join(''));
        iframe.contentDocument.close();
    },
    setOasData : function(data){
        this.setState({
            oasData : JSON.parse(data)
        });
    },
    componentDidMount : function(){
        var url = "getJsonDataUrl";

        var xhttp = new XMLHttpRequest();
        var changeOasDataFunction = this.setOasData;
        xhttp.onreadystatechange = function () {
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                changeOasDataFunction(xhttp.responseText);
            }
        };
        xhttp.open("GET", url, true);
        xhttp.send();
    },
    render : function(){
        return (
            <MyIframe refs="bannerIframe" onLoad={this.iframeOnLoad} />
        );
    }
});

module.exports = Display;

我做错了什么?

最佳答案

TLDR;

Edit react-iframe-examples

如果您正在寻找一种方法来控制 <iframe> 的内容通过 React 以事实上的规范方式,Portals是要走的路。 与所有 Portal 一样:一旦您建立了对现有且已安装的 DOM 节点的引用(在本例中,这将是给定 <iframe>contentWindow )并且 用它创建一个 Portal,它的内容也被视为“父”虚拟 DOM 的子项,这意味着共享(合成)事件系统、上下文等。

请注意,为了代码简洁,下面的示例使用 Optional chaining operator , 截至撰写本文时,并非所有浏览器都支持。

示例:一个功能性 React 组件,包括 hooks :

// iframe.js

import React, { useState } from 'react'
import { createPortal } from 'react-dom'

export const IFrame = ({
  children,
  ...props
}) => {
  const [contentRef, setContentRef] = useState(null)
  const mountNode =
    contentRef?.contentWindow?.document?.body

  return (
    <iframe {...props} ref={setContentRef}>
      {mountNode && createPortal(children, mountNode)}
    </iframe>
  )
}

示例:React 类组件:

// iframe.js

import React, { Component } from 'react'
import { createPortal } from 'react-dom'

export class IFrame extends Component {
  constructor(props) {
    super(props)
    this.state = {
      mountNode: null
    }
    this.setContentRef = (contentRef) => {
      this.setState({
        mountNode: contentRef?.contentWindow?.document?.body
      })
    }
  }

  render() {
    const { children, ...props } = this.props
    const { mountNode } = this.state
    return (
      <iframe
        {...props}
        ref={this.setContentRef}
      >
        {mountNode && createPortal(children, mountNode)}
      </iframe>
    )
  }
}

用法:

import { IFrame } from './iframe'

const MyComp = () => (
    <IFrame>
        <h1>Hello Content!</h1>
    </IFrame>
)

进一步控制,例如对 <iframe> 的控制<head>内容,可以很容易地实现为 this Gist显示。

还有react-frame-component ,恕我直言,这个包提供了很多 使用受控时所需的一切 <iframe> React 中的 s。

注意事项:

  • 此答案仅涉及用例,其中给定 <iframe> 的所有者想要以类似 React 的方式以编程方式控制(如决定)其内容。
  • 此答案假设 <iframe> 的所有者符合Same-origin policy .
  • 此答案不适合跟踪外部资源在 <iframe src="https://www.openpgp.org/> 中的加载方式和时间。一种场景。
  • 如果您关心可访问性,您应该为您的 iframe 提供 meaningful title attributes .

用例(我所知道的);

  • OP 的用例:广告以及控制广告如何以及何时访问您网站上安全范围内的元素的需要。
  • 可嵌入的第三方小部件。
  • 我的用例(以及我对此事的一些知情立场):CMS UI,您希望用户能够预览范围内的 CSS 样式,包括应用的媒体查询。

将一组给定的 CSS 样式(或样式表)添加到受控 <iframe> :

正如一位评论作者指出的那样,管理父应用程序和受控 <iframe> 的内容之间的样式可能相当棘手。 如果您足够幸运,拥有一个专门的 CSS 文件,其中包含您的 <iframe> 的所有必要的视觉说明。 ,可能就足够了 通过您的IFrame组件a <link>标签引用所述样式,尽管这不是最符合标准的方式 <link>引用文献:

const MyComp = () => (
  <Frame>
    <link rel="stylesheet" href="my-bundle.css">
    <h1>Hello Content!</h1>
  </Frame>
) 
然而,在当今时代,尤其是在 React 世界中,大多数时候,build设置会动态创建样式和样式表: 因为他们利用 SASS 等元语言,甚至使用 CSS-in-JS 等更复杂的解决方案( styled-componentsemotion )。

此沙箱包含如何在 React 中将一些更流行的样式策略与 iframe 集成的示例。

Edit react-iframe-examples

这个答案还提供了有关 16.3 之前的 React 版本的秘诀。然而,在这个时候,我认为可以肯定地说,大多数 我们能够实现一个 React 版本,包括 Portals,以及较小程度的 hooks。如果您需要有关 iframe 和 React 版本 < 16 的解决方案, 联系我,我很乐意提供建议。

关于javascript - 如何设置react组件的iframe内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34743264/

相关文章:

javascript - 为 svg 元素中的文本标签添加样式

javascript - iframe视频的替代图片

javascript - 通过单击 IFrame(内联框架)中的项目,我需要路由到特定的 URL

javascript - 向 'textAlign' 提供失败的 prop 类型 : Invalid props. 样式 key 'View'

javascript - MobX 存储在 React Native 中未更新

javascript - React 中如何判断哪个组件触发了事件处理器?

javascript - 向数据表添加页面控件,但当代码运行时,页面中没有显示任何内容

javascript - 将 Facebook 的移动托管 API 与应用链接的解析云代码结合使用

用户与 Iframe 中的对象交互后 JavaScript 确认离开

javascript - 如何让 Greasemonkey 重定向到本地资源?