如何在next.js中显示HTML内容

问题描述 投票:0回答:2

我想在 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>
,所以它应该在页面上显示文本,但是我得到了这个白屏。

这是我看到的白屏 enter image description here

这是我的文件目录:

enter image description here

html reactjs next.js
2个回答
0
投票

您需要使

index.html
可从 Next.js 应用程序访问。如果
index.html
不在公共目录中,则 fetch 调用将无法访问它,因为它没有作为静态文件公开。然后,获取 URL 应正确指向此文件,如
/index.html

index.html
移至
public
文件夹。静态文件应该放在
public
目录


0
投票
您的应用无法访问位于

index.html

 文件夹中的 
pages
文件。

您可以尝试执行以下操作来使其可下载:

  1. 移动到您的页面(index.html 文件)到
    public
    文件夹。将文件重命名为
    template.html
    );
  2. const response = await fetch('index.html');
    修改为
    const response = await fetch('/template.html');
    。 `
© www.soinside.com 2019 - 2024. All rights reserved.