我想通过componentDidMount()
方法获取地图实例,但未成功。
请参见以下代码,我想通过
获取地图实例const map = this.context[MAP];
但是if情况始终为假。顺便说一句,ref中的el
始终是未定义的。
import React, { Component } from 'react';
import {compose, withProps, onlyUpdateForPropTypes} from "recompose";
import {withScriptjs, withGoogleMap, GoogleMap, Marker} from 'react-google-maps';
import {MAP} from 'react-google-maps/lib/constants';
import PropTypes from "prop-types";
const MyMapComponent = compose(
withProps({
googleMapURL: "https://maps.googleapis.com/maps/api/js?key=v2&libraries=places,geometry,drawing",
loadingElement: <div style={{height: '100%'}} />,
containerElement: <div style={{height: '800px'}} />,
mapElement: <div style={{height: '100%'}} />,
}),
withScriptjs,
withGoogleMap
)(props =>
<GoogleMap
defaultZoom={15}
defaultCenter={{lat: 47.6129432, lng: -122.9716967}} >
</GoogleMap>
);
export default class MapContainer extends Component {
static contextTypes = { [MAP]: PropTypes.object };
render() {
return (
<MyMapComponent
ref={(el) => {this.mapNode = el}} />
)
}
componentDidMount() {
console.log("Entry into componentDidMount : " + this.mapNode);
if (this.context[MAP]) {
const map = this.context[MAP];
console.log("The map instance is: " + map);
}
}
}
有人知道如何通过componentDidMount()
方法获取地图实例吗?