reactjs 下载.html文件时保留样式(React)

thtygnil  于 2023-05-17  发布在  React
关注(0)|答案(1)|浏览(230)

下面是我的React组件的简化版本:

export class SomePage extends Component {

  downloadAsHTML() {
    const element = document.createElement("a");

    const file = new Blob([document.getElementById('second-child-div').outerHTML], {
      type: "text/html"
    });

    element.href = URL.createObjectURL(file);
    element.download = "file.html";
    document.body.appendChild(element);
    element.click();
  }

  render () {
    return (
      <>
        <div className="first-child-div">Stuff here</div>
        <div id="second-child-div" onClick={()=>this.downloadAsHTML()}>
           <span className="some-other-styling-here">
              <h1> Title </h1>
              <p> Paragraph </p>
              More things here
           </span>
           More html elements, nested styling, and text here
        </div>
      </>
    )
  }

}

当用户单击second-child-div并将div作为.html文件下载时,我希望下载的.html文件保留所有classNameshtml选择器的样式(如.css中的#second-child-div h1)。最好的办法是什么?
我考虑的一种方法是创建另一个名为Styles.js的文件:

const Styles = {
  container: {
    'padding': '30px',
    'border'
  },
  anotherContainer:  {
    'color': 'blue',
    'background': 'yellow'
  }
  containerH1: {
    'font-size': '20px'
  }
  containerParagraph: {
    'font-size': '20px'
  },
}

export default Styles;

然后按如下方式导入:

import "Styles" from "./Styles.js"

//in second-child-div:

<div id="second-child-div" style={Styles.container} onClick={()=>this.downloadAsHTML()}>
   <span style={Styles.anotherContainer}>
      <h1 style={Styles.containerH1}> Title </h1>
      <p style={Styles.containerParagraph}> Paragraph </p>
       More things here
   </span>
   More html elements, nested styling, and text here
</div>

在我的实际应用程序中,我有几十个样式,css选择器等。最有效的方法是什么?

t1rydlwq

t1rydlwq1#

您可以在单击按钮时将CSS加载到页面中,然后在保存之前将CSS内联到<style>标记内的HTML文件中。
这种方法是蛮力的。我并不试图找出哪些样式适用于您要导出的元素,它只是获取所有样式。

const downloadAsHTML = () => {
  const element = document.createElement("a");

  const domNodeToSave = document.getElementById("second-child-div");
  const modifiedDomNodeToSave = domNodeToSave.cloneNode(true);
  modifiedDomNodeToSave.style.margin =
    "10px"; // example modificaiton

  const htmlSnippet = modifiedDomNodeToSave.outerHTML;

  const styleSheets = document.styleSheets;

  let allStyles = "";

  for (let i = 0; i < styleSheets.length; i++) {
    const styleSheet = styleSheets[i];

    const rules = styleSheet.cssRules;

    for (let j = 0; j < rules.length; j++) {
      const rule = rules[j];

      allStyles += rule.cssText + "\n";
    }
  }

  const styleBlock = `<style>${allStyles}</style>`;
  htmlSnippet += styleBlock;

  const file = new Blob([htmlSnippet], {
    type: "text/html",
  });

  element.href = URL.createObjectURL(file);
  element.download = "file.html";
  document.body.appendChild(element);
  element.click();
};

相关问题