2

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

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 包创意表单,但没有任何成功。

任何人以前都以某种方式服用过这个,即使有人成功了一个页面并且无能为力?!

谢谢

4

0 回答 0