Typescript+React封装路由拦截组件
需求:离开切换页面检测是否保存,点击确认跳转相应路由,取消则留在本页
react-router取消了路由守卫,自带组件Prompt可以进行路由拦截,后面借助antd的Modal封装成弹窗组件
import { Modal } from 'antd'
import * as React from 'react'
import { Prompt, useHistory } from 'react-router'
interface IRouterPromptProps {
isBlock: boolean
title?: string
content?: string
onOk?: () => void
}
/**
* 路由拦截组件
* 监听页面跳转是否需要保存信息
*/
export const RouterPrompt = React.memo((props: IRouterPromptProps) => {
const history = useHistory()
const [isBlock, setIsBlock] = React.useState(props.isBlock)
React.useEffect(() => {
setIsBlock(props.isBlock)
}, [props.isBlock])
const handleClick = (location: any, action: string, type: string) => {
if (type === 'ok') {
setTimeout(() => {
if (action === 'POP') {
history.goBack()
} else if (action === 'PUSH') {
history.push(location)
} else {
history.replace(location)
}
}, 100)
setIsBlock(false)
// console.log('我已确认')
}
}
return (
<Prompt
when={isBlock}
message={(location, action) => {
Modal.confirm({
title: props.title ? props.title : '提醒',
content: props.content ? props.content : '修改的内容尚未保存,是否继续',
okText: '确定',
cancelText: '取消',
onOk: () => handleClick(location, action, 'ok'),
onCancel: () => handleClick(location, action, 'cancel')
})
return false
}}
/>
)
})
export default RouterPrompt
使用:在需要拦截的页面导入,在任一处使用
import RouterPrompt from 'yourroute/RouterPrompt' <RouterPrompt isBlock title="提醒" content="修改的内容尚未保存,是否继续" />