react-router 4中离开确认自定义

在有些应用中,产品需求是这样的:例如-用户详情编辑页 当用户跳转路由时,需要提示用户当前页面的数据尚未保存,提示用户离开确认。

大概效果如图:


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(
      <Prompt message="确定要离开?"  when={true}/>
  )
}

其中message可以为:

  1. message: string
    当用户离开当前页面时,设置的提示信息。
    <Prompt message="确定要离开?" />

  2. message: func
    当用户离开当前页面时,设置的回掉函数
    <Prompt message={location => (
    Are you sue you want to go to ${location.pathname}?
    )} />

  3. 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 = () => (
    <div>组件一</div>
)
const MyComponent2 = () => (
    <div>组件二</div>
)
class MyComponent extends React.Component {
    render() {
        const getConfirmation = (message,callback) => {
            const ConFirmComponent = () => (
                <div>
                    {message}
                    <button onClick={() => {callback(true);ReactDOM.unmountComponentAtNode(document.getElementById('root'))}}>确定</button>
                    <button onClick={() => {callback(false);ReactDOM.unmountComponentAtNode(document.getElementById('root'))}}>取消</button>
                </div>
            )
            ReactDOM.render(
                <ConFirmComponent />,
                document.getElementById('root1')
            )
        }
        return (
            <Router getUserConfirmation={getConfirmation}>
                <div>
                    <Prompt message="Are you sure you want to leave?" />
                    <Link to="/a">跳转组件二</Link>
                    <Route component={MyComponent1}/>
                    <Route exact path="/a" component={MyComponent2}/>
                </div>
            </Router>
        )
    }
}
ReactDOM.render(
    <MyComponent/>,
    document.getElementById('root')
)

更多 react-router的api介绍可以看文章

react-router4相关属性api介绍

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容