【问题标题】:How to load a local html file inside an iframe in my react application?如何在我的 React 应用程序中的 iframe 中加载本地 html 文件?
【发布时间】:2023-01-04 20:10:23
【问题描述】:

在使用创建的 React 应用程序中尝试从我的公共文件夹加载 html 文件时遇到问题创建反应应用程序.我在 webpack 的某处缺少配置设置吗?

我目前有这个文件夹结构:

我想在我的 React 组件中的 Iframe 中显示 test.html 文件,如下所示:

import React from 'react';

const Component = props => {
  return (<iframe src="/test/index.html"title="Docuvieware" />);
};

export default Component;

但这在 Iframe 中给了我一个“Cannot GET /test/index.html”。直接冲浪时也可以http://localhost:3000/test/index.html我收到一个白页,上面写着“无法获取/test/index.html”

我也尝试使用“process.env.PUBLIC_URL”在我的组件中,但这是未定义的。

【问题讨论】:

  • http://localhost:3000/test/index.html那个呢?
  • 这会将我重定向到一个显示“无法获取/test/index.html”的白页
  • 如果您只需要此页面来测试您的 iframe,我建议使用 react-router 并在您的应用程序中为其创建路由...我正在以这种方式测试我的 iframe。
  • 您不需要为 iframe 进行额外设置。看起来 publicpath 没有解决。尝试使用“/public/test/index.html” 如果不更新 cra

标签: javascript reactjs webpack iframe


【解决方案1】:

我已经设法通过使用来解决这个问题复制WebpackPlugin. 刚刚在我的 src 文件夹中添加了测试文件夹,然后将以下行添加到我的 webpack 配置中:

new CopyWebpackPlugin([{ from: 'src/test', to: 'test' }]),

然后 /test/index.html 给出了正确的路径。

【讨论】:

    【解决方案2】:

    代码的最简单版本可能看起来像这样。

    在 webpack 配置中执行下一步。

    const path = require('path');
    paths.root = path.resolve(__dirname, '..');
    paths.publicFiles = path.join(paths.root, 'public');
    paths.test = path.join(paths.publicFiles, 'test');
    
    plugins: [
      new CopyWebpackPlugin([
        { path.join(paths.test, 'index.html'), to: 'src/test-frame.html' }
      ])
    ] 
    

    然后在您的组件中使用下一行(如果需要,更改 localhost):

    <iframe
      src="http://localhost:3000/src/test-frame.html"
      id="unique-id"
      title="Frame test"
      // remove these styles later
      style={{ minHeight: `50vh`, width: '100vw' }}
    />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      • 2023-03-10
      • 2022-01-26
      • 2015-02-21
      • 1970-01-01
      • 2019-10-19
      • 1970-01-01
      相关资源
      最近更新 更多