【问题标题】:Next JS: Import an html file to component prior to exporting project as static HTMLNext JS:在将项目导出为静态 HTML 之前将 html 文件导入组件
【发布时间】:2018-10-12 01:00:37
【问题描述】:

我目前正在使用next export 创建预渲染的 HTML。我面临的问题是我需要在导出之前将现有的标头 HTML 文件导入到我的组件中。此标头 HTML 文件也位于与我的 dist 文件夹无关的目录中。

假设我的 dist 文件在这个子目录中: www.mysite.com/myproject/

我需要导入的标头位于此处: www.mysite.com/htmls/nav/header.html

有没有办法在将其导出为静态 html 页面之前导入并显示此 header.html?提前谢谢!

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    有两种方法可以实现您的目标:

    使用Javascript

    <script>
    function includeHeader() {
      var z, i, elmnt, file, xhttp;
      /*loop through a collection of all HTML elements:*/
      z = document.getElementsByTagName("*");
      for (i = 0; i < z.length; i++) {
        elmnt = z[i];
        /*search for elements with a certain atrribute:*/
        file = elmnt.getAttribute("w3-include-html");
        if (file) {
          /*make an HTTP request using the attribute value as the file name:*/
          xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function() {
            if (this.readyState == 4) {
              if (this.status == 200) {elmnt.innerHTML = this.responseText;}
              if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
              /*remove the attribute, and call this function once more:*/
              elmnt.removeAttribute("w3-include-html");
              includeHTML();
            }
          } 
          xhttp.open("GET", file, true);
          xhttp.send();
          /*exit the function:*/
          return;
        }
      }
    }
    </script>
    

    然后调用它

    <script>
       includeHeader();
    </script>
    

    使用 HTML

    <div w3-include-html="/htmls/nav/header.html"></div>
    

    【讨论】:

      猜你喜欢
      • 2021-12-06
      • 2020-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-13
      • 2022-11-14
      相关资源
      最近更新 更多