如何在react.js中使用iframe

时间:2018-09-14 03:41:46

标签: javascript reactjs

我怎样才能通过iframe从public /中获取html?

我的代码如下:

App.js

import React, {Component} from 'react';
import Iframe from './IframeComm';

class App extends Component {
    render() {
        return (
            <div className="App">
                <h1>react</h1>
                <Iframe
                    attributes={
                        {
                            src: '/test/test.html',
                            style: {
                                border: '10px solid red'
                            },
                        }
                    }
                />
            </div>
        );
    }
}

export default App;

test.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    iframe
</body>
</html>

使用npm start时,一切正常

enter image description here

但是当我使用npm run build

enter image description here

目录:

enter image description here

我该如何解决?谢谢。

2 个答案:

答案 0 :(得分:1)

您可以简单地创建一个新组件,该组件可以获取源代码并以Iframe返回;

iframe.js

import React from 'react';

const Iframe = ({ source }) => {

    if (!source) {
        return <div>Loading...</div>;
    }

    const src = source;     
    return (
        // basic bootstrap classes. you can change with yours.
        <div className="col-md-12">
            <div className="emdeb-responsive">
                <iframe src={src}></iframe>
            </div>
        </div>
    );
};

export default Iframe;

然后您可以像这样简单地调用该组件;

import React, {Component} from 'react';
import Iframe from './components/iframe.js';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            src: '/test/test.html'
        };
    }

    render() {
        return (
            <div className="App">
                <h1>react</h1>
                <Iframe source={this.state.src} />
            </div>
        );
    }
}

export default App;

答案 1 :(得分:0)

如果要将html保留在公用文件夹中,请执行axios调用,将html加载到变量中并在src中提供它,

var myhtml;
axios.get('/test/test.html').then((resp)=>{
  myhtml = resp.data;
})
...
<Iframe
attributes={
              {
                 src: {myhtml},
                 style: {
                          border: '10px solid red'
                        },
               }
            }
 />

或者,您可以将htmlfile添加到src文件夹而不是public,并像完成操作一样使用它。