react中路由跳转前确认

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

    <!-- 作者区域 -->
    <div class="author">
      <a class="avatar" href="/u/5c13b327009c">

    <!-- 文章内容 -->
    <div data-note-content="" class="show-content">
      <div class="show-content-free">
        <p>在有些应用中,产品需求是这样的:例如-用户详情编辑页  当用户跳转路由时,需要提示用户当前页面的数据尚未保存,提示用户离开确认。</p>

大概效果如图:


之前router-router的做法是:

路由钩子:
 componentDidMount() {
 this.props.router.setRouteLeaveHook(
        this.props.routes[1],
        this.routerWillLeave()
 )}

routerWillLeave() { return false} ture为离开,false为留下

而在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时启用防止转换;

但是,直接这样用的话,页面默认弹出的是这样的效果:

不符合我们的产品设计需求。

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('root1'))}}>确定</button>
                    <button onClick={() => {callback(false);ReactDOM.unmountComponentAtNode(document.getElementById('root1'))}}>取消</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介绍

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值