我正在使用反应门户来呈现我的反应视图的可打印版本。这就是我所做的:
import { Component } from "react";
import ReactDOM from "react-dom";
export default class PortalWindow extends Component {
container = document.createElement("div");
externalWindow = null;
componentDidMount() {
this.externalWindow = window.open();
this.externalWindow.document.body.appendChild(this.container);
}
componentWillUnmount() {
this.externalWindow.close();
}
render() {
return ReactDOM.createPortal(this.props.children, this.container);
}
}
import React from 'react';
import './order-print.css';
function OrderPrint(props) {
return (
<div className="order-print">
</div>
);
}
export default OrderPrint;
还有一个名为PurchaseOrder的组件,我在其中执行以下操作:
class PurchaseOrder extends React.Component {
...//omitted for brevity
render(){
{this.state.shouldPrint && (
<PortalWindow>
<OrderPrint order={order} />
</PortalWindow>
)}
}
}
因此,只需单击一个按钮,我就可以将shouldPrint
状态更改为 true,并且可打印版本将显示在新窗口中。但是,import './order-print.css';
语句似乎没有效果,因此该样式未应用于我的 OrderPrint.jsx 文件中的div。
以下是order-print.css
文件的内容:
.order-print{
border:3 px solid red;
}
所以显然,react 不会将 css 传递给在新窗口中加载的视图。有没有办法使这成为可能。
我实际上已经尝试使用style
而不是className
并引用具有样式信息的 const 对象,事实上,它可以工作。 但这只是我更喜欢使用类而不是内联样式。
这样的事情对我有用:
componentDidMount() {
this.externalWindow = window.open();
// find the existing style tags in the parent window
const styleTagsInHead = window.document.head.getElementsByTagName("style");
// clone them
const styles = Array.from(styleTagsInHead).map(style => style.cloneNode());
// and add them to the new child window
this.externalWindow.document.head.append(...styles);
this.externalWindow.document.body.appendChild(this.container);
}
注意!您可能需要更改查询样式标记的方式,具体取决于样式在应用程序中的应用方式。