前言:
項目有個需求是:跳轉路由,在離開頁面前,須要彈框詢問用戶是否肯定離開。
用react-router
的<Prompt>
組件是能夠的,可是,怎麼使用antd
組件(或者說自定義組件)呢?
請看下面react
先看的這個:https://stackoverflow.com/questions/32841757/detecting-user-leaving-page-with-react-router
(1)使用react-router
的<Prompt>
antd
import { Prompt } from 'react-router' <Prompt message="你肯定要離開嘛?" />
(2)<Prompt>
支持函數react-router
<Prompt when={true} message={(location) => { return window.confirm(`confirm to leave to ${location.pathname}?`); }} />
(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>
組件順序執行呢?this
說白點就是,<Modal>
組件先顯示出來,阻塞後面的 return false/true,等 <Modal>
組件的 onOk、onCancel 方法執行後,再 return false/truespa
我試了幾種方法,不行,直到找到這篇文章:
Using React-Router v4 Prompt with custom modal componentcode
(4)在離開頁面,路由跳轉時,自定義彈框攔截,並詢問component
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>
完美實現離開頁面,路由攔截的同時,顯示自定義模態框!router
(完)路由