javascript - 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
纳入该事件处理程序感到困惑。
解决方案
您可以先将组件的“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();
// ==============================
}
});
}
}
}
推荐阅读
- javascript - 重写reduce方法js的问题
- angular - Nativescript + Angular ScrollView 滚动到最终监听器
- java - 如何在JAVA中动态转义JSON中的双引号
- java - Spring Data Rest:发布与非导出实体相关的实体
- python - 如何按其键内的值对字典进行排序?
- visual-studio - 如何在 Azure DevOps 上克隆项目?
- python - 在 Python 中使用 ibm_db_dbi 调用带有数组参数的 DB2 存储过程
- python - 在 Django 中实现足球场地预订系统
- php - 如何解决“参数必须是实现可数的数组或对象?”
- java - 如果这不是线程安全的,我可以通过哪些方式使其成为线程安全的?