https://www.npmjs.com/package/react-router-navigation-prompt
https://github.com/ZacharyRSmith/react-router-navigation-prompt

离开页面时二次确认弹窗,可以自定义弹窗内容。

使用

  1. import React from 'react';
  2. import { Modal } from 'antd';
  3. import NavigationPrompt from 'react-router-navigation-prompt';
  4. interface CustomPromptProps {
  5. visible?: boolean;
  6. exclusion?: string[]; // 排除的路由列表
  7. }
  8. const CustomPrompt: React.FC<CustomPromptProps> = ({ visible = true, exclusion }) => {
  9. return (
  10. <NavigationPrompt
  11. allowGoBack={true}
  12. when={(prevLocation, nextLocation) => {
  13. const { pathname = '' } = nextLocation || {};
  14. const isExclusion = /^\/user\//.test(pathname) || exclusion?.includes(pathname);
  15. return visible && !isExclusion;
  16. }}
  17. >
  18. {({ onConfirm, onCancel }) => (
  19. <Modal
  20. visible
  21. onOk={onConfirm}
  22. onCancel={onCancel}
  23. title="你即将离开页面"
  24. maskClosable={false}
  25. >
  26. 离开页面会丢失当前页面的内容,确定要离开吗?
  27. </Modal>
  28. )}
  29. </NavigationPrompt>
  30. );
  31. };
  32. export default CustomPrompt;