将iframe插入反应组件

我有一个小问题.在从服务请求数据后,我得到了一个iframe代码作为响应.
<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>

我想把它作为道具传递到我的模态组件并显示它但是当我只是{this.props.iframe}它在渲染函数中它显然是将它显示一个字符串.

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

解决方法

您可以使用属性 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作为字符串),其中包含< iframe>标记并将其传递给新的< 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>

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些