繁体   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