react页面切换弹窗提醒

本文介绍了两种页面保存和切换时的提醒解决方案。一种是在页面刷新时利用'beforeunload'事件监听,防止数据丢失;另一种是通过路由守卫 Prompt 实现页面切换确认,确保用户在离开前保存更改。代码示例详细展示了这两种方法的实现过程。
摘要由CSDN通过智能技术生成

页面保存提醒

解决方案:

1.当页面不切换,仅刷新时,页面效果如图

实现原理:窗口关闭事件-beforeunload,在组件挂载时监听事件,组件卸载时移除事件监听
代码实现:

Editor = () => {
		const listener = ev => {
		    ev.preventDefault();
		    ev.returnValue='are you sure?';
		};
		window.addEventListener('beforeunload', listener);
		return () => {
		    window.removeEventListener('beforeunload', listener)
		}
	}
	componentDidMount() {
		this.Editor()
	}
	componentWillUnmount() {
		this.Editor()
	}

2.当页面切换时,页面效果如图

实现原理:路由守卫<Prompt/>--使用<Prompt/>,路由跳转必须通过<Link/>实现,而不能依靠<a/>原生标签。点击取消时就会留在当前页面
代码实现:

import {Button,Modal} from 'antd';
import { Prompt } from 'react-router'
class Email extends React.Component {
    showModalSave = location => {    
		this.setState({
			modalVisible: true,      
			location,    
		});  
	};  
	closeModalSave = () => {    
		const { location } = this.state;    
		const { history } = this.props; 
		this.isSave = false;   
		history.push({      
			pathname: `..${location.pathname}`,    
		});  
		this.setState({
			modalVisible: false,    
		}); 
	};  
	handlePrompt = location => {    
		if (!this.isSave) {   
			this.showModalSave(location);      
			return false;    
		}    
		return true;  
	};  
	handleSave = () => {    
		const { location } = this.state;    
		const { history } = this.props;   
		this.isSave = true;    
		history.push({      
			pathname: `..${location.pathname}`,    
		});    
		this.setState({      
			modalVisible: false,    
		});   
		// this.saveAll();  
	}; 
    return (
        <Prompt message={this.handlePrompt}/>
				<Modal 
				//   title="提示"       
				  visible={this.state.modalVisible}       
				  onCancel={this.closeModalSave}       
				//   closable={false}       
				  centered 
				  width={400}      
				  footer={null}>
					<div style={{fontColor:'#1F1F1F',textAlign: 'center',height: 100,lineHeight:'100px', padding: 0 }}>Save the current Settings?</div>
					<div style={{display: 'flex', padding: '0 26px' }}>      
						<Button style={{marginRight:60}} block size='large' type='ghost' onClick={this.closeModalSave}>Discard</Button>       
						<Button block size='large' type='primary' onClick={this.handleSave}>Save</Button>
					</div>
				</Modal>
    )

}


export default Email;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值