在React Component Lifecycle Hook内的`this`的作用域问题

时间:2019-06-26 16:03:41

标签: javascript reactjs inheritance scope react-router

我有一个像这样定义的React类组件:

JS

  o
 \|/
 / \

正如您从注释中看到的那样,我在生命周期挂钩中有一个构造函数,用于创建OverlayView的新实例。因此,当我在MapOverlay的方法和事件处理程序中进行编写时,我就超出了搜索组件的范围。

我的问题

如何在<?php session_start(); require 'conn.php'; ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); if($_SERVER["REQUEST_METHOD"] == "POST"){ $maile = $_POST["maile"]; $password = $_POST["password"]; $con = mysqli_connect('localhost','u3970232106_donat','jesu'); $query = "SELECT * FROM `users` WHERE `maile` = '$maile'"; $result = mysqli_query($con, $query); $hashed = password_hash($password, PASSWORD_DEFAULT); if(password_verify($_POST["password"],$hashed)) { header("location: home.php"); }else{ echo 'wrong'; } } ?> 事件处理程序(位于OverlayView的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. } }); } } } 方法内部)中调用Search的道具?

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

1 个答案:

答案 0 :(得分:1)

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