Javascript React组件生命周期挂钩内的'this'范围问题
我有一个React类组件,定义如下: JS 正如您从注释中看到的,我在生命周期钩子中有一个构造函数,它正在创建OverlayView的新实例。因此,当我在MapOverlay的方法和事件处理程序中编写时,我被带出了搜索组件的范围 我的问题 如何从Javascript React组件生命周期挂钩内的'this'范围问题,javascript,reactjs,inheritance,scope,react-router,Javascript,Reactjs,Inheritance,Scope,React Router,我有一个React类组件,定义如下: JS 正如您从注释中看到的,我在生命周期钩子中有一个构造函数,它正在创建OverlayView的新实例。因此,当我在MapOverlay的方法和事件处理程序中编写时,我被带出了搜索组件的范围 我的问题 如何从click事件处理程序(位于OverlayView的onAdd()方法中)内部调用搜索的道具 我是否需要创建另一个名为MapOverlay的组件,然后将历史传递到该组件中?我只是不知道如何将this的范围获取到该事件处理程序中。您可以首先将组件的“thi
click
事件处理程序(位于OverlayView的onAdd()方法中)内部调用搜索的道具
我是否需要创建另一个名为MapOverlay的组件,然后将历史传递到该组件中?我只是不知道如何将this
的范围获取到该事件处理程序中。您可以首先将组件的“this”存储在一个变量中。您可以在componentDidMount()中访问它在MyOverlay范围之外。之后,您可以随时使用它
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();
// ==============================
}
});
}
}
}
我现在不能测试它,但我一有机会就会给你回复。我觉得这是一个非常简单的解决方案,可以解决一个我认为会更大的问题。:D
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();
// ==============================
}
});
}
}
}