将iframe插入到react组件中

将iframe插入到react组件中,iframe,reactjs,Iframe,Reactjs,我有个小问题。从服务请求数据后,我得到了一个iframe代码作为响应 <iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe> 我想把它作为一个道具传递给我的模态组件并显示它,但是当我在渲染函数中简单地{this.props.iframe}它时,它显然是以字符串的形式显示的 在react中将其显示为html的基本方式是什么?您可以使用属性,如下所示 c

我有个小问题。从服务请求数据后,我得到了一个iframe代码作为响应

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

我想把它作为一个道具传递给我的模态组件并显示它,但是当我在渲染函数中简单地
{this.props.iframe}
它时,它显然是以字符串的形式显示的

在react中将其显示为html的基本方式是什么?

您可以使用属性,如下所示

const Component=React.createClass({
iframe:function(){
返回{
__html:this.props.iframe
}
},
render:function(){
返回(
);
}
});
常量iframe='';
ReactDOM.render(
,
document.getElementById('容器')
);

如果您不想使用危险的LysetinerHTML,那么您可以使用下面提到的解决方案

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')
);
var Iframe=React.createClass({
render:function(){
报税表(
)
}
});
ReactDOM.render(
,
document.getElementById('示例')
);

这里提供了ES6的实时演示

,您现在可以这样做了

要加载的代码笔URl示例

const iframe = '<iframe height="265" style="width: 100%;" scrolling="no" title="fx." src="//codepen.io/ycw/embed/JqwbQw/?height=265&theme-id=0&default-tab=js,result" frameborder="no" allowtransparency="true" allowfullscreen="true">See the Pen <a href="https://codepen.io/ycw/pen/JqwbQw/">fx.</a> by ycw(<a href="https://codepen.io/ycw">@ycw</a>) on <a href="https://codepen.io">CodePen</a>.</iframe>'; 
const iframe='查看上的ycw()笔';
加载Iframe的功能组件

function Iframe(props) {
  return (<div dangerouslySetInnerHTML={ {__html:  props.iframe?props.iframe:""}} />);
}
函数Iframe(道具){
返回();
}
用法:

import React from "react";
import ReactDOM from "react-dom";
function App() {
  return (
    <div className="App">
      <h1>Iframe Demo</h1>
      <Iframe iframe={iframe} />,
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
从“React”导入React;
从“react dom”导入react dom;
函数App(){
返回(
Iframe演示
,
);
}
const rootElement=document.getElementById(“根”);

ReactDOM.render(

这并不是我不想使用它,我不是100%确定它怎么会出错。你的解决方案是干净的,我只需要解析字符串来提取值。根据我在React to use DangerouslySetinerHTML中的理解,使用危险的HTML不是一个好的做法,如果你认为我的解决方案是一个答案,那么接受它感谢这段代码。这是总比使用好dangersoulySetHtml@DhavalPatel这个解决方案很好,但是,基于这个问题,这并不能解决问题-在从服务请求数据后,我得到了一个iframe代码作为响应-似乎iframe是一个字符串,在这种情况下如何呈现它?@AlexanderT:你能发布一些你想要呈现的代码吗考虑一下使用这种方式的缺点是什么?
听起来很危险
听起来很危险……好吧……危险只有当你能很好地控制你正在“iframing”的内容时,才使用危险的LysetinerHTML,否则它会让你的用户面临跨站点脚本(XSS)攻击。