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

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;

我做错了什么?

推荐答案

太长,读不下go 了

Edit react-iframe-examples

如果你正在寻找一种方法,以一种事实上的规范方式控制<iframe> via React的内容,那么Portals是最好的 Select .

请注意,为了代码简洁,下面的示例使用了Optional chaining operator

Example:A 102包括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>
  )
}

Example:A 101:

// 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>
    )
  }
}

Usage:

import { IFrame } from './iframe'

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

进一步的控制,例如对<iframe>s <head>内容的控制,可以容易地实现如下:

还有react-frame-component个,这是imho提供的基本套餐

Caveats:

  • 这个答案只针对特定<iframe>的所有者希望以编程方式控制(比如决定)其内容的用例.
  • 这个答案假设<iframe>的所有者符合Same-origin policy.
  • 这个答案不适合跟踪<iframe src="https://www.openpgp.org/>种场景中外部资源的加载方式和加载时间.
  • 如果可访问性是你关心的事情,你应该给你的iframes meaningful title attributes.

Use cases (that I know of);

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

Adding a given set of CSS styles (or stylesheets) to a controlled 100:

正如一位 comments 作者所指出的,在父应用程序和受控<iframe>的内容之间管理样式可能相当棘手.

const MyComp = () => (
  <Frame>
    <link rel="stylesheet" href="my-bundle.css">
    <h1>Hello Content!</h1>
  </Frame>
) 

然而,在当今时代,尤其是在React世界,大多数时候,构建设置会动态创建样式和样式表:

这个Sandbox 包含了如何将一些更流行的造型策略与React中的iFrame相结合的示例.

Edit react-iframe-examples

该答案还用于给出16.3之前版本的React的配方.然而,在这个时候,我认为可以肯定地说

Reactjs相关问答推荐

在迁移到Redux—Toolkit 2.0和Redux5.0之后,我在extraReducer和Slice方面有点挣扎,

在react中向数组状态添加值时出错

两条react 路由的行为不同.有没有人能解释一下,我已经找了好几天了

值在返回页面时不更新,即使我已经更新了它们

如何在物料界面react 的多选菜单中设置最大 Select 数限制

Gitlab CI和VITE环境变量出现问题

React useEffect 问题...异步函数内的变量正在获取延迟的更新值

如何获取用户在 GooglePlacesAutocomplete 中输入的文本?

找不到名称setCometChat

尽管所有页面在 Reactjs 中都是公开的,但始终导航到特定页面

标签文本删除了 MUI 概述的输入

为 Next.js 应用程序目录中的所有页面添加逻辑的全局文件是什么?

useEffect 内的 onClick 和 addEventListener 之间的 click 事件顺序差异

useMemo 依赖项的行为

如何在Next.js应用程序中为路由[slug]生成.html文件?

React 应用程序可以嵌入到 PowerPoint 中吗?

如何在 ChartJS 中操作 Y 轴

NextJS htaccess 设置

如何在 Cypress E2E 的站点上测试react 组件?

如何实现两个 SVG 形状相互叠加的 XOR 操作?