你可以使用财产dangerouslySetInnerHTML
,就像这样
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>
个标记的string(based on the question, you get iframe as a string from a server)中复制所有属性,并将其传递给新的<iframe>
标记,如下所示
/**
* 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>