首页 > 解决方案 > 如何从打开窗口的组件中获取新窗口对象的引用?

问题描述

我想使用此库https://github.com/rmariuzzo/react-new-window来聚焦窗口,只要单击表中的行就会打开该窗口。.focus()通过调用创建的窗口对象有一个方法window.open()。如何获取窗口对象的引用,以便可以调用.focus()

标签: reactjswindow.open

解决方案


我试图做类似的事情,但希望弹出窗口在打开时打印出来。

这是解决方案(使用 React 钩子):

import React, {useEffect, useRef} from 'react';
import NewWindow from "react-new-window";

const PopupWindow = () => {
    const thisWindow = useRef(null);

    // This will fire when thisWindow reference changes.
    useEffect(() => {
        thisWindow.current.window.focus();
        // thisWindow.current.window.print();  // To print when the popup window loads.
    }, [thisWindow]);

    return (
        <>
            <NewWindow
                ref={thisWindow}
            >
                <p>
                   Your content here
                </p>
            </NewWindow>
        </>
    )
}

export default PopupWindow;

推荐阅读