我想在 next.js 中显示 HTML 文件的内容。我了解到可以在 App.js 中使用angerlySetInnerHTML 来实现此目的。
但是,我在使用它时总是出现白屏。我尝试将 GET 请求发送到 index.html 文件,但我一直看到白屏。
App.js
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [htmlContent, setHtmlContent] = useState('');
useEffect(() => {
async function fetchHtml() {
try {
const response = await fetch('index.html');
const html = await response.text();
setHtmlContent(html);
} catch (error) {
console.error('Error fetching HTML file:', error);
}
}
fetchHtml();
}, []);
return (
<div dangerouslySetInnerHTML={{ __html: htmlContent }} />
);
}
export default MyComponent;
我的index.html只有样板代码和
<p>Hello World</p>
,所以它应该在页面上显示文本,但是我得到了这个白屏。
这是我的文件目录:
您需要使
index.html
可从 Next.js 应用程序访问。如果 index.html
不在公共目录中,则 fetch 调用将无法访问它,因为它没有作为静态文件公开。然后,获取 URL 应正确指向此文件,如 /index.html
。
将
index.html
移至 public
文件夹。静态文件应该放在public
目录
index.html
文件夹中的
pages
文件。
您可以尝试执行以下操作来使其可下载:
public
文件夹。将文件重命名为 template.html
);const response = await fetch('index.html');
修改为const response = await fetch('/template.html');
。
`