reactjs 如何在react应用程序的iframe中加载本地html文件?

a9wyjsp7  于 2023-01-04  发布在  React
关注(0)|答案(2)|浏览(579)

尝试从使用create-react-app创建的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中给了我一个“无法获取/test/index. html”。而且当直接浏览http://localhost:3000/test/index.html时,我得到了一个白色页面,上面写着“无法获取/test/index. html”
我还尝试在我的组件中使用**“process.env.PUBLIC_URL”**,但这是未定义的。

f0brbegy

f0brbegy1#

我已经设法通过使用CopyWebpackPlugin修复了这个问题。只是在我的src文件夹中添加了test文件夹,然后在我的webpack配置中添加了以下行:

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

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

gudnpqoy

gudnpqoy2#

代码的最简单版本可能看起来像这样。
在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' }}
/>

相关问题