0

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

无法读取未定义的属性“地图”。在此处输入图像描述

怎么了?

4

1 回答 1

1

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

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

需要替换为:

addMarker.bind(this)({ lat: 50.4418782, lng: 30.5107196 });
于 2018-04-30T13:01:34.733 回答