简体   繁体   中英

Scope Issue With `this` Inside React Component Lifecycle Hook

I have a React class component defined like so:

JS

import { Component } from 'react';

export class Search extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    MyOverlay.prototype = new google.maps.OverlayView();
    let map = MyOverlay();
    function MyOverlay() {
      // constructor
      ...
    }

    MyOverlay.prototype.onAdd = () => {

      // I need this from OverlayView
      let panes = this.getPanes(); 

      // Another place where I need `this`
      let div = document.createElement('div');
      this.div_ = div;

      // Attach an Event Handler to the Overlay
      google.maps.event.addDomListener(this.div_, 'click', () => {

          // I need access to the props belonging to the Search Component, 
          //   but, now, using `.bind(this)` is out of the question because the 
          //   outer function needs access to OverlayView's `this`
          this.props.history.push(); // `this` is now out of scope.
        }
      });
    }
  }
}

As you can see from the comments, I have a constructor inside a lifecycle hook that is creating a new instance of OverlayView. Because of that, I'm taken out of the scope of the Search Component when I'm writing inside the methods and event handlers of MapOverlay.

My Question

How can I call the props of Search from inside the click event handler (which is inside the OverlayView's onAdd() method?

Do I need to create another component called MapOverlay and then pass history into that? I'm just confused as to how I'm going to get the scope of this into that event handler.

You can just store the 'this' of the component first at a variable. You can access it inside componentDidMount() outside the MyOverlay scope. Afterwards, you can use it whenever you want.

import { Component } from 'react';

export class Search extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    MyOverlay.prototype = new google.maps.OverlayView();
    let map = MyOverlay();
    function MyOverlay() {
      // constructor
      ...
    }

    // ===== store it first here ====
    let history = this.props.history;
    // ==============================

    MyOverlay.prototype.onAdd = () => {
      let panes = this.getPanes(); 
      let div = document.createElement('div');
      this.div_ = div;
      google.maps.event.addDomListener(this.div_, 'click', () => {

          // ===== history of the Search component =====
          history.push();
          // ==============================
        }
      });
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM