在有些应用中,产品需求是这样的:例如-用户详情编辑页 当用户跳转路由时,需要提示用户当前页面的数据尚未保存,提示用户离开确认。
大概效果如图:
image.png
之前router-router的做法是:
路由钩子:
componentWillMount(){
this.context.router.setRouteLeaveHook(
this.props.route,
this.routerWillLeave
)
}
routerWillLeave( nextLocation ){
return `页面即将从Home切换到${nextLocation.pathname}`
}
而在react-router 4中 是:
使用Prompt 组件:
import { Prompt } from 'react-router-dom';
....
render(){
return(
)
}
其中message可以为:
message: string
当用户离开当前页面时,设置的提示信息。
message: func
当用户离开当前页面时,设置的回掉函数
(
Are you sue you want to go to ${location.pathname}?
)} />
when: bool
通过设置一定条件要决定是否启用 Prompt,属性值为true时启用防止转换;
但是,直接这样用的话,页面默认弹出的是这样的效果:
image.png
不符合我们的产品设计需求。
1. 自定义
直接上demo
import React from 'react'
import ReactDOM from 'react-dom'
import { Prompt } from 'react-router'
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
const MyComponent1 = () => (
)
const MyComponent2 = () => (
)
class MyComponent extends React.Component {
render() {
const getConfirmation = (message,callback) => {
const ConFirmComponent = () => (
{message}
{callback(true);ReactDOM.unmountComponentAtNode(document.getElementById('root'))}}>确定
{callback(false);ReactDOM.unmountComponentAtNode(document.getElementById('root'))}}>取消
)
ReactDOM.render(
,
document.getElementById('root1')
)
}
return (
跳转组件二
)
}
}
ReactDOM.render(
,
document.getElementById('root')
)
更多 react-router的api介绍可以看文章