我参考了react-google-maps 文档中关于如何实现 ref 的示例。请参阅此链接上的工作示例和下面的代码片段:
import React from "react";
const { compose, withProps, withState, withHandlers } = require("recompose");
const {
withScriptjs,
withGoogleMap,
GoogleMap,
Marker,
InfoWindow
} = require("react-google-maps");
const MapWithControlledZoom = compose(
withProps({
googleMapURL:
"https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry,drawing,places",
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `400px` }} />,
mapElement: <div style={{ height: `100%` }} />
}),
withState("zoom", "onZoomChange", 8),
withHandlers(() => {
const refs = {
map: undefined
};
return {
onMapMounted: () => ref => {
refs.map = ref;
},
onZoomChanged: () => () => {
console.log(refs.map.getZoom());
console.log(refs.map.getCenter());
}
};
}),
withScriptjs,
withGoogleMap
)(props => (
<GoogleMap
defaultCenter={{ lat: -34.397, lng: 150.644 }}
zoom={props.zoom}
ref={props.onMapMounted}
onZoomChanged={props.onZoomChanged}
/>
));
export default MapWithControlledZoom;