将iframe插入反应组件 [英] Inserting the iframe into react component
问题描述
我有一个小问题。在从服务请求数据后,我得到了一个iframe代码作为回应。
I have a small problem. After requesting a data from a service I got an iframe code in response.
<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>
我想将此作为道具传递到我的模态组件并显示它但是当我只是 {this.props.iframe}
它在渲染功能中显然将其显示为字符串。
I would like to pass this in as a props to my modal component and display it but when I simply {this.props.iframe}
it in the render function it is obviously displaying it as a string.
在反应中以html形式显示它的基本方法是什么?
推荐答案
您可以使用属性 dangerouslySetInnerHTML
,像这样
You can use property dangerouslySetInnerHTML
, like this
const Component = React.createClass({
iframe: function () {
return {
__html: this.props.iframe
}
},
render: function() {
return (
<div>
<div dangerouslySetInnerHTML={ this.iframe() } />
</div>
);
}
});
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>';
ReactDOM.render(
<Component iframe={iframe} />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
此外,你可以复制字符串中的所有属性(基于问题,您将iframe作为来自服务器的字符串),其中包含< iframe>
标记并将其传递给新的< iframe>
标记,就像那样
also, you can copy all attributes from the string(based on the question, you get iframe as a string from a server) which contains <iframe>
tag and pass it to new <iframe>
tag, like that
/**
* getAttrs
* returns all attributes from TAG string
* @return Object
*/
const getAttrs = (iframeTag) => {
var doc = document.createElement('div');
doc.innerHTML = iframeTag;
const iframe = doc.getElementsByTagName('iframe')[0];
return [].slice
.call(iframe.attributes)
.reduce((attrs, element) => {
attrs[element.name] = element.value;
return attrs;
}, {});
}
const Component = React.createClass({
render: function() {
return (
<div>
<iframe {...getAttrs(this.props.iframe) } />
</div>
);
}
});
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>';
ReactDOM.render(
<Component iframe={iframe} />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"><div>
这篇关于将iframe插入反应组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!