簡體   English   中英

React 組件生命周期鈎子中`this` 的范圍問題

[英]Scope Issue With `this` Inside React Component Lifecycle Hook

我有一個像這樣定義的 React 類組件:

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.
        }
      });
    }
  }
}

正如您從評論中看到的,我在生命周期鈎子中有一個構造函數,用於創建 OverlayView 的新實例。 因此,當我在 MapOverlay 的方法和事件處理程序中編寫內容時,我被排除在搜索組件的范圍之外。

我的問題

如何從click事件處理程序內部(在 OverlayView 的onAdd()方法中onAdd()調用 Search 的道具?

我是否需要創建另一個名為 MapOverlay 的組件,然后將歷史記錄傳遞給它? 我只是對如何將this的范圍放入該事件處理程序感到困惑。

您可以先將組件的“this”存儲在一個變量中。 您可以在 MyOverlay 范圍之外的 componentDidMount() 內部訪問它。 之后,您可以隨時使用它。

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();
          // ==============================
        }
      });
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM