react脱离页面,自定义弹框阻拦,路由阻拦

《react脱离页面,自定义弹框阻拦,路由阻拦》

媒介:
项目有个需求是:跳转路由,在脱离页眼前,须要弹框讯问用户是不是肯定脱离。
react-router<Prompt>组件是能够的,然则,怎样运用antd组件(或者说自定义组件)呢?
请看下面

先看的这个:https://stackoverflow.com/questions/32841757/detecting-user-leaving-page-with-react-router
(1)运用react-router<Prompt>

import { Prompt } from 'react-router'

<Prompt
  message="你肯定要脱离嘛?"
/>

《react脱离页面,自定义弹框阻拦,路由阻拦》

(2)<Prompt>支撑函数

<Prompt
  when={true}
  message={(location) => {
    return window.confirm(`confirm to leave to ${location.pathname}?`);
  }}
/>

《react脱离页面,自定义弹框阻拦,路由阻拦》

(3)history.block这个是个坑!

import { history } from 'path/to/history';
class MyComponent extends React.Component {
   componentDidMount() {
      history.block(targetLocation => {
           // take your action here     
           return false;
      });
   }
   render() {
      //component render here
   }
}

坑的原因是history.block()要领是不能和<Modal>组件并列运用的,而必须在history.block()内部去挪用<Modal>组件(就是解释take your action here那边),这就致使一个题目:<Modal>组件里的 onOk、onCancel 怎样返回值给 history.block()的 return 语句(return false/true)的同时,不让history.block()的 return 语句和 <Modal>组件递次实行呢?

说白点就是,<Modal>组件先显现出来,壅塞背面的 return false/true,等 <Modal>组件的 onOk、onCancel 要领实行后,再 return false/true

我试了几种要领,不可,直到找到这篇文章:
Using React-Router v4 Prompt with custom modal component

(4)在脱离页面,路由跳转时,自定义弹框阻拦,并讯问

  handlePrompt = location => {
    if (!this.isSave) {
      this.showModalSave(location);
      return false;
    }
    return true;
  };

  showModalSave = location => {
    this.setState({
      modalVisible: true,
      location,
    });
  };

  closeModalSave = () => {
    const { location } = this.state;
    const { history } = this.props;
    this.setState({
      modalVisible: false,
    });
    history.push({
      pathname: `..${location.pathname}`,
    });
  };

  handlePrompt = location => {
    if (!this.isSave) {
      this.showModalSave(location);
      return false;
    }
    return true;a
  };

  handleSave = () => {
    const { location } = this.state;
    const { history } = this.props;
    this.isSave = true;
    console.log(location.pathname, 'pathname75');
    history.push({
      pathname: `..${location.pathname}`,
    });
    this.setState({
      modalVisible: false,
    });
    this.saveAll();
  };

 <Prompt message={this.handlePrompt}/>
<Modal title="提醒"
       visible={modalVisible}
       onCancel={this.closeModalSave}
       closable={false}
       centered
       footer={null}
>
<div>是不是保留修正?</div>
<div>
      <Button onClick={this.closeModalSave}>
            不保留
      </Button>
       <Button onClick={this.handleSave}>
            保留
       </Button>
</div>
</Modal>

《react脱离页面,自定义弹框阻拦,路由阻拦》

圆满完成脱离页面,路由阻拦的同时,显现自定义模态框!

《react脱离页面,自定义弹框阻拦,路由阻拦》

(完)

    原文作者:小进进
    原文地址: https://segmentfault.com/a/1190000019105896
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞