【问题标题】:Google-maps-react doesn't work谷歌地图反应不起作用
【发布时间】:2018-04-27 10:47:44
【问题描述】:

我有 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:

无法读取未定义的属性“地图”。 enter image description here

怎么了?

【问题讨论】:

    标签: reactjs google-maps-react


    【解决方案1】:

    React 中,函数不会自动绑定到组件实例(documentation),它们需要显式绑定。您可以使用 bind 函数,在提供的示例中,该行:

    addMarker({lat: 50.4418782,lng: 30.5107196});
    

    需要替换为:

    addMarker.bind(this)({ lat: 50.4418782, lng: 30.5107196 });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 1970-01-01
      相关资源
      最近更新 更多