react離開頁面,自定義彈框攔截,路由攔截

前言:
項目有個需求是:跳轉路由,在離開頁面前,須要彈框詢問用戶是否肯定離開。
react-router<Prompt>組件是能夠的,可是,怎麼使用antd組件(或者說自定義組件)呢?
請看下面javascript

先看的這個:stackoverflow.com/questions/3…
(1)使用react-router<Prompt>java

import { Prompt } from 'react-router'

<Prompt
  message="你肯定要離開嘛?"
/>
複製代碼

(2)<Prompt>支持函數react

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

(3)history.block這個是個坑!antd

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>組件順序執行呢?react-router

說白點就是,<Modal>組件先顯示出來,阻塞後面的 return false/true,等 <Modal>組件的 onOk、onCancel 方法執行後,再 return false/trueapp

我試了幾種方法,不行,直到找到這篇文章:
Using React-Router v4 Prompt with custom modal component函數

(4)在離開頁面,路由跳轉時,自定義彈框攔截,並詢問ui

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

  showModalSave = location => {
    this.setState({
      modalVisibletrue,
      location,
    });
  };

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

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

  handleSave = () => {
    const { location } = this.state;
    const { history } = this.props;
    this.isSave = true;
    console.log(location.pathname, 'pathname75');
    history.push({
      pathname`..${location.pathname}`,
    });
    this.setState({
      modalVisiblefalse,
    });
    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>
複製代碼

完美實現離開頁面,路由攔截的同時,顯示自定義模態框!this


(完)spa

相關文章
相關標籤/搜索