我正在尝试在 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;
我究竟做错了什么?
// 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> ) }
// 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> )