与打字稿反应关闭标签/窗口

时间:2019-03-31 17:02:05

标签: reactjs typescript browser-close

我需要一个自定义对话框,以在用户关闭浏览器选项卡或窗口时显示。 我试图编写一个包装我的应用程序的组件。 这是我尝试的方式:

import * as PropTypes from 'prop-types';
import * as React from 'react';
import WindowsCloseDialog from './desktop/windowsClose.dialog';

interface IProps
{
    onBeforeunload?: () => void;
}

interface IState
{}

const Dialog = (): JSX.Element => <WindowsCloseDialog />

class Beforeunload extends React.Component<IProps, IState>
{
    // Things to do before unloading/closing the tab
    doSomethingBeforeUnload = () =>
    {
        // Do something
    }

    // Setup the `beforeunload` event listener
    setupBeforeUnloadListener = () =>
    {
        window.addEventListener('beforeunload', (e: BeforeUnloadEvent) =>
        {
            e.preventDefault();
            return this.doSomethingBeforeUnload();
        });
    };

    componentDidMount = (): void =>
    {
        // Activate the event listener
        this.setupBeforeUnloadListener();
    }

    render()
    {
        const { children = null } = this.props;
        return children === null || children === undefined ? Dialog() : children;
    }
}

export default Beforeunload;

然后我包装了我的应用程序:

const container =
      <Beforeunload onBeforeunload={ () => 'Test'}>
        <AppContainer>
          <Router history={ history }>
            <IndexRoutes/>
          </Router>
        </AppContainer>
      </ Beforeunload>

const ROOT = document.getElementById('root');

ReactDOM.render(container, ROOT);

页面已加载,但是当我关闭窗口/选项卡时没有消息。 我试图用字符串消息替换Dialog(),但没有成功。

我在这里尝试了npm package想法表,但没有成功。

任何人都以某种方式使用过此药物,即使有人成功完成某页并且无法帮助?!

thnx

0 个答案:

没有答案