https://www.npmjs.com/package/react-router-navigation-prompt
https://github.com/ZacharyRSmith/react-router-navigation-prompt
离开页面时二次确认弹窗,可以自定义弹窗内容。
使用
import React from 'react';
import { Modal } from 'antd';
import NavigationPrompt from 'react-router-navigation-prompt';
interface CustomPromptProps {
visible?: boolean;
exclusion?: string[]; // 排除的路由列表
}
const CustomPrompt: React.FC<CustomPromptProps> = ({ visible = true, exclusion }) => {
return (
<NavigationPrompt
allowGoBack={true}
when={(prevLocation, nextLocation) => {
const { pathname = '' } = nextLocation || {};
const isExclusion = /^\/user\//.test(pathname) || exclusion?.includes(pathname);
return visible && !isExclusion;
}}
>
{({ onConfirm, onCancel }) => (
<Modal
visible
onOk={onConfirm}
onCancel={onCancel}
title="你即将离开页面"
maskClosable={false}
>
离开页面会丢失当前页面的内容,确定要离开吗?
</Modal>
)}
</NavigationPrompt>
);
};
export default CustomPrompt;