2015-11-25 30 views
7

我有一个小问题。在请求服务中的数据之后,我得到了一个iframe代码作为回应。将iframe插入反应组件

<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe> 

我想作为一个道具它传递给我的模态分量并显示,但是当我只是{this.props.iframe}它在渲染功能很明显是显示它作为一个字符串。

什么是反应显示它为html的基本方法?

回答

13

您可以使用属性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作为来自服务器的字符串),其中包含标记并将其传递给新的标记,就像那样

/** 
 
* 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>

18

如果你不想使用dangerouslySetInnerHTML那么你可以使用下面提及的解决方案

var Iframe = React.createClass({  
    render: function() { 
    return(   
     <div>   
     <iframe src={this.props.src} height={this.props.height} width={this.props.width}/>   
     </div> 
    ) 
    } 
}); 

ReactDOM.render(
    <Iframe src="http://plnkr.co/" height="500" width="500"/>, 
    document.getElementById('example') 
); 

这里现场演示,请Demo

+0

它不是我不想使用它我不能100%确定它会出错。你的解决方案是干净的我只是需要我解析字符串来提取值。 – Kocur4d

+0

根据我的理解在React使用危险SetInnerHTML是不是一个好的做法和雅如果你认为我的解决方案将是一个答案,然后接受它 –

+2

感谢您的代码..这比使用dangersoulySetHtml – John