|
1 | 1 | import React, { Fragment, createFactory } from 'react'; |
| 2 | +import PropTypes from 'prop-types'; |
2 | 3 | import { Prompt as ReactRouterPrompt } from 'react-router'; |
3 | 4 | import invariant from 'invariant'; |
4 | 5 |
|
@@ -76,13 +77,48 @@ export const withGoodBye = BaseRouterComponent => { |
76 | 77 | return WithGoodBye; |
77 | 78 | }; |
78 | 79 |
|
79 | | -export default ({ when = false, children }) => { |
80 | | - return ( |
81 | | - <Fragment> |
82 | | - <ReactRouterPrompt when={when} message="" /> |
83 | | - <GoodByeContext.Consumer> |
84 | | - {renderProps => children({ ...renderProps })} |
85 | | - </GoodByeContext.Consumer> |
86 | | - </Fragment> |
87 | | - ); |
| 80 | +class GoodBye extends React.Component { |
| 81 | + handleBeforeUnload = evt => { |
| 82 | + const { alertMessage } = this.props; |
| 83 | + evt.returnValue = alertMessage; |
| 84 | + return alertMessage; |
| 85 | + }; |
| 86 | + |
| 87 | + componentDidUpdate() { |
| 88 | + const { when, alertBeforeUnload } = this.props; |
| 89 | + window.onbeforeunload = when && alertBeforeUnload |
| 90 | + ? this.handleBeforeUnload |
| 91 | + : null; |
| 92 | + } |
| 93 | + |
| 94 | + componentWillUnmount() { |
| 95 | + window.onbeforeunload = null; |
| 96 | + } |
| 97 | + |
| 98 | + render() { |
| 99 | + const { when, children } = this.props; |
| 100 | + return ( |
| 101 | + <Fragment> |
| 102 | + <ReactRouterPrompt when={when} message="" /> |
| 103 | + <GoodByeContext.Consumer> |
| 104 | + {renderProps => children({ ...renderProps })} |
| 105 | + </GoodByeContext.Consumer> |
| 106 | + </Fragment> |
| 107 | + ); |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +GoodBye.propTypes = { |
| 112 | + when: PropTypes.bool, |
| 113 | + alertBeforeUnload: PropTypes.bool, |
| 114 | + alertMessage: PropTypes.string, |
| 115 | + children: PropTypes.func.isRequired, |
| 116 | +}; |
| 117 | + |
| 118 | +GoodBye.defaultProps = { |
| 119 | + when: false, |
| 120 | + alertBeforeUnload: false, |
| 121 | + alertMessage: '' // only work for IE |
88 | 122 | }; |
| 123 | + |
| 124 | +export default GoodBye; |
0 commit comments