React组件卸载、路由跳转、页面关闭(刷新)之前进行提示
时间: 2023-08-04 22:02:45 浏览: 37
可以使用React Router提供的Prompt组件来实现在路由跳转或页面关闭前进行提示。在Prompt组件中设置message属性为提示信息,当用户尝试进行路由跳转或关闭页面时,会弹出提示框询问用户是否确定离开当前页面。在组件卸载时,可以在componentWillUnmount生命周期函数中弹出提示框进行提示。同时,可以使用beforeunload事件来监听页面关闭或刷新事件,并在事件回调函数中弹出提示框。
下面是一个示例代码:
```javascript
import React, { Component } from 'react';
import { Prompt } from 'react-router-dom';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
showPrompt: false
};
}
componentDidMount() {
window.addEventListener('beforeunload', this.handleBeforeUnload);
}
componentWillUnmount() {
window.removeEventListener('beforeunload', this.handleBeforeUnload);
}
handleBeforeUnload = (e) => {
if (this.state.showPrompt) {
e.preventDefault();
e.returnValue = '';
}
}
handleButtonClick = () => {
this.setState({ showPrompt: true });
}
handlePromptCancel = () => {
this.setState({ showPrompt: false });
}
render() {
return (
<div>
<Prompt
when={this.state.showPrompt}
message="确定要离开吗?"
/>
<button onClick={this.handleButtonClick}>离开</button>
</div>
);
}
}
```
在上面的代码中,我们定义了一个MyComponent组件,其中包含一个离开按钮。当用户点击离开按钮时,会将showPrompt属性设置为true,从而触发Prompt组件的显示。当用户尝试进行路由跳转或关闭页面时,会弹出提示框询问用户是否确定离开当前页面。在组件卸载时,我们移除beforeunload事件的监听器。同时,在事件回调函数中,如果showPrompt属性为true,则阻止默认行为并将returnValue属性设置为空字符串,从而触发提示框的显示。