reactjs - 谷歌地图反应不起作用
问题描述
我有 MapContainer:
import React, { Component } from "react";
import ReactDOM from "react-dom";
export class MapContainer extends Component {
componentDidUpdate(props) {
this.loadMap();
}
loadMap() {
if (this.props && this.props.google) {
const {google} = this.props;
const maps = google.maps;
const mapRef = this.refs.map;
const node = ReactDOM.findDOMNode(mapRef);
const mapConfig = Object.assign({}, {
center: {lat: 50.4418782, lng: 30.5107196},
zoom: 15,
})
this.map = new maps.Map(node, mapConfig);
addMarker({lat: 50.4418782,lng: 30.5107196});
function addMarker(coords) {
const marker = new google.maps.Marker({
position: coords,
map: this.map
});
}
}
}
render() {
const style = {
width: '100%',
height: '40rem',
margin: '2rem auto'
};
return (
<div ref="map" style={style}>
loading map...
</div>
)
}
}
export default MapContainer;
当它开始我有TypeError:
无法读取未定义的属性“地图”。在此处输入图像描述
怎么了?
解决方案
InReact
函数不会自动绑定到组件实例(文档),它们需要显式绑定。您可以bind
为此使用函数,在提供的示例中,该行:
addMarker({lat: 50.4418782,lng: 30.5107196});
需要替换为:
addMarker.bind(this)({ lat: 50.4418782, lng: 30.5107196 });
推荐阅读
- xamarin.forms - Xamarin Forms:WebView 加载时间非常长
- nestjs - Nestjs 和类验证器 - 至少一个字段不应为空
- blank-line - 如何在每行之间系统地添加新行
- php - php 错误未捕获的错误:调用未定义的函数 mysqli_fetch_all()
- android - 使用 NullPointerException 权限调用 LocationUpdatesService 时应用程序崩溃
- java - 根据 args 具有不同 EditText 的 DetailFragment
- javascript - 当我想返回匿名类型时,函数说返回布尔值
- node.js - 如何修复 Broccoli Builder 在 Ember 应用程序中遇到 `UglifyWriter` 插件错误
- python - 当我想停止它时,线程不会停止
- xpages - 基于 xPages 的论坛