首页 > 解决方案 > React 组件生命周期钩子中的 `this` 范围问题

问题描述

我有一个这样定义的 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()方法内部)调用 Search 的道具?

我是否需要创建另一个名为 MapOverlay 的组件,然后将历史传递给该组件?我只是对如何将范围this纳入该事件处理程序感到困惑。

标签: javascriptreactjsinheritancescopereact-router

解决方案


您可以先将组件的“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();
          // ==============================
        }
      });
    }
  }
}

推荐阅读