React Portals - 执行引用新窗口 DOM 的函数

问题描述 投票:0回答:1

我正在尝试创建一个 React Portal,安装后需要运行特定行来加载 ActiveReports Designer 组件。

这是我的门户代码:

constructor(props: IWindowPortalProps) {
        super(props);
        this.containerEl = document.createElement('div'); // STEP 1: create an empty div
        this.containerEl.id = 'designer-host';
        this.containerEl.className = styles.designerHost;
        this.externalWindow = null;
    }

    private copyStyles = (sourceDoc: Document, targetDoc: Document) => {
        Array.from(sourceDoc.styleSheets).forEach(styleSheet => {
            if (styleSheet.cssRules) { // true for inline styles
                const newStyleEl = sourceDoc.createElement('style');

                Array.from(styleSheet.cssRules).forEach(cssRule => {
                    newStyleEl.appendChild(sourceDoc.createTextNode(cssRule.cssText));
                });

                targetDoc.head.appendChild(newStyleEl);
            } else if (styleSheet.href) { // true for stylesheets loaded from a URL
                const newLinkEl = sourceDoc.createElement('link');

                newLinkEl.rel = 'stylesheet';
                newLinkEl.href = styleSheet.href;
                targetDoc.head.appendChild(newLinkEl);
            }
        });
    }

    componentDidMount() {
        this.externalWindow = window.open('', '', `height=${window.screen.height},width=${window.screen.width}`);
        this.externalWindow.document.body.appendChild(this.containerEl);

        this.externalWindow.document.title = 'A React portal window';
        
        this.externalWindow.addEventListener('load', () => {
            new Designer('#designer-host');    
        });
    }

    render() {
        return ReactDOM.createPortal(null, this.containerEl);
    }

但是,当加载新窗口时,我收到错误

Error: Cannot find the host element. at Function.<anonymous>

这表明

designer-host
div 不存在。我认为加载函数指向主 DOM,而不是新窗口的 DOM。

或者,我尝试通过在我的 componentDidMount() 中执行操作来附加 ActiveReports .js 文件

s.type = "text/javascript";
s.src = "../node_modules/@grapecity/activereports/lib/node_modules/@grapecity/ar-js-designer/index.js";
this.externalWindow.document.head.append(s);

然后在元素的 onLoad 属性上分配 Designer 实例化。再次没有运气。

有没有一种方法可以在门户加载后运行 JavaScript 代码并指向该 DOM?

javascript reactjs activereports react-portal
1个回答
-1
投票

我在葡萄城工作。您可以访问我们的支持门户并提交票证吗?我们需要完整的代码示例才能回答这个问题。请向我们提供票证中示例的下载链接。

谢谢你

© www.soinside.com 2019 - 2024. All rights reserved.