zoukankan      html  css  js  c++  java
  • [React] Setup 'beforeunload' listener

    In this lesson we'll show how to take a beforeUnload call and convert it to a declarative React Component. It will handle subscribing to events, and automatically unsubscribing to prevent memory leaks.

    class BeforeUnload extends React.Component {
    
      constructor(props) {
        super(props);
        this.alertMessage = this.alertMessage.bind(this);
      }
    
      componentDidMount() {
        window.addEventListener("beforeunload", this.alertMessage);
      }
      
      componentDidUpdate(prevProps, prevState) {
        const { active } = this.props;
        const { active: wasActive } = prevProps;
    
        if (wasActive && !active) {
          window.removeEventListener("beforeunload", this.alertMessage);
        } else if (!wasActive && active) {
          window.addEventListener("beforeunload", this.alertMessage);
        }
      }
      
      componentWillUnmount() {
        window.removeEventListener("beforeunload", this.alertMessage);
      }
    
      alertMessage(e) {
        if (this.props.active) {
          e.returnValue = true;
          return true;
        }
      }
      
    
      render() {
        return this.props.children;
      }
    }
    
    class App extends React.Component {
      
      constructor(props) {
        super(props);
        this.state = {
          active: true,
        }
        this.toggle = this.toggle.bind(this);
      }
      
      toggle() {
        this.setState((state) => { 
            return { active: !state.active } 
          }
        );
      }
      
      render() {
        return (
          <BeforeUnload active={this.state.active}>
            <button onClick={this.toggle}>{this.state.active ? "Active": "Inactive"}</button>
          </BeforeUnload>
        );
      }
    }
    
    ReactDOM.render(
      <App />,
      document.getElementById('example')
    );

  • 相关阅读:
    1052: 最大报销额
    1036: 小希的数表
    1050: 找出直系亲属
    1048: 导弹防御系统
    1051: 魔咒词典
    以大数据眼光欣赏唐人文墨(一)
    Java 内部类详解
    那些“不务正业”的IT培训公司
    Brackets 前端编辑器试用
    Emmet 快速编写html代码
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6973154.html
Copyright © 2011-2022 走看看