【问题标题】:Render HTML inside a React app using iframe使用 iframe 在 React 应用程序中渲染 HTML
【发布时间】:2018-07-30 23:43:04
【问题描述】:

我有一个 React 组件,我想在其中渲染一些静态 HTML。这是我的 React 组件外观的 sn-p:

class MyComponent extends Component {
    render() {
        return (
            <div>
                <iframe title="static_html" src="static_html_in_react_project.html"></iframe>
            </div>
        );
    }
}

我只有一个基本的 HTML 文件,如下所示:

<html>
    <head>
        <title>HTML</title>
        <script src="http://code.jquery.com/jquery-1.11.3.min.js" type="text/javascript"></script>
    </head>
    <body>
        Do some stuff here
    </body>
</html>

但是,当我使用 React 组件时,它似乎无法正常工作,因为它只是在 iframe 内重新呈现同一页面。我已将静态 HTML 文件放在 public 以及与调用组件相同的目录中,它会一遍又一遍地渲染父组件。

任何人有任何解决方案来呈现来自同一个 React 项目的iframe 中的静态文件?

【问题讨论】:

    标签: javascript reactjs iframe


    【解决方案1】:

    我遇到了同样的问题。可以通过将外部 html 文件与index.html 一起放在公共文件夹中来解决。此解决方案有效。如果 html 文件位于 src 文件夹中,它不会以某种方式提取并呈现它们。

    我在项目中使用 webpack 和 babel。 如果你想要一个示例项目来尝试一下,试试这个 https://github.com/grommet/grommet-vending 将外部文件放入 public 文件夹,并在 src 中放入一个带有 iframe 的页面。

    当您在 iframe 中添加文件地址时,请使用

    src="../App_File.html"
    

    【讨论】:

    • 这似乎在生产中无效,知道如何让它在生产中工作吗?
    【解决方案2】:

    为此有一个 NPM 包。 查看react-iframe

    https://www.npmjs.com/package/react-iframe

    【讨论】:

    • 这实际上和我上面的代码是一样的。它不是加载位于项目中的静态 html 文件,而是实际上一遍又一遍地渲染父容器。
    • 只是想回帖说我正在探索什么可行,什么不在这里......这是我目前正在阅读的关于 React 和 iframe 的文章:medium.com/@ebakhtarov/…
    猜你喜欢
    • 2010-12-19
    • 2018-01-20
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多