使用 React Portal 时将 css 注入到 window.document

2024-01-21

我正在使用反应门户来呈现我的反应视图的可打印版本。这就是我所做的:

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 file:

.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);
    }

Note!您可能需要更改查询样式标签的方式,具体取决于应用程序中应用样式的方式。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 React Portal 时将 css 注入到 window.document 的相关文章

随机推荐