首页 文章

将iframe插入反应组件

提问于
浏览
19

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

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

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

What is the base way to display it as html in react?

2 回答

  • 26

    您可以使用属性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>
    

    另外,你可以复制 string 中的所有属性(基于问题,你从服务器得到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>
    
  • 22

    如果您不想使用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

相关问题