要求是我需要初始化一个react组件而不更新DOM
print() {
let toPrint = ReactDOMServer.renderToString(<ComponentToPrint0 />); // Returns string
toPrint += ReactDOMServer.renderToString(<ComponentToPrint1 />);
printHandler(toPrint);
}
printHandler(htmlElement) {
let tempWindow = window.open();
tempWindow.document.write('<html><head><title>Print</title>');
tempWindow.document.write('<link rel="stylesheet" href="http://localhost:9595/app/main.css" type="text/css" />');
tempWindow.document.write('</head><body>');
tempWindow.document.write(htmlElement);
tempWindow.document.write('</body></html>');
tempWindow.focus();
tempWindow.print();
tempWindow.close();
}
在上面的ComponentToPrint0和ComponentToPrint1以字符串形式返回时,这是更好的方法还是其他方法?
答案 0 :(得分:1)
它可以被视为任何其他React应用程序:
const Popup = () => <>
<head>
<title>Print</title>
<link rel="stylesheet" href="http://localhost:9595/app/main.css" type="text/css" />
</head>
<body>
<ComponentToPrint0 />
<ComponentToPrint1 />
</body>
</>;
...
let tempWindow = window.open();
ReactDOM.render(<Popup/>, tempWindow.document.documentElement);
tempWindow.focus();
tempWindow.print();
tempWindow.close();