内容简介:前言:项目有个需求是:
前言:
项目有个需求是: 跳转路由,在离开页面前,需要弹框询问用户是否确定离开。
用 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="你确定要离开嘛?"
/>
(2) <Prompt> 支持函数
<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> 组件顺序执行呢?
说白点就是, <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离开页面,自定义弹框拦截,路由拦截》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- 前端架构之vue+axios 前端实现登录拦截(路由拦截、http拦截)
- 如何实现一个react-router路由拦截(导航守卫)
- Springboot整合Hibernate拦截器时无法向拦截器注入Bean
- 基于原生fetch封装一个带有拦截器功能的fetch,类似axios的拦截器
- SpringMVC拦截器
- IOS 拦截器
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
C++ Primer 中文版(第 4 版)
Stanley B.Lippman、Josée LaJoie、Barbara E.Moo / 李师贤、蒋爱军、梅晓勇、林瑛 / 人民邮电出版社 / 2006 / 99.00元
本书是久负盛名的C++经典教程,其内容是C++大师Stanley B. Lippman丰富的实践经验和C++标准委员会原负责人Josée Lajoie对C++标准深入理解的完美结合,已经帮助全球无数程序员学会了C++。本版对前一版进行了彻底的修订,内容经过了重新组织,更加入了C++ 先驱Barbara E. Moo在C++教学方面的真知灼见。既显著改善了可读性,又充分体现了C++语言的最新进展和当......一起来看看 《C++ Primer 中文版(第 4 版)》 这本书的介绍吧!