【发布时间】:2016-04-17 01:04:14
【问题描述】:
我正在尝试在 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 元素中还是要自己设置/组合 IFrame 内容?
-
嗨 Lukas,我必须自己设置内容。在我的情况下,我对服务器进行 ajax 调用以取回一些数据。这个“somedata”有一个我需要设置到 iframe 中的脚本。
标签: javascript iframe reactjs xmlhttprequest