-2

我正在尝试访问地图的当前缩放或中心,但我遇到了一些错误。我是 React 新手,我不确定自己在做什么,但我尝试将 ref 附加到 GoogleMap 组件

const refMap = useRef(null);

const handleZoomChanged = () => {
    const newZoom = refMap.current.getZoom();
    console.log(newZoom);
  }

...

<GoogleMap
          ref={refMap}
          {...mapProps}
          center={mapCenter}
          zoom={mapCenter.zoom}
          onZoomChanged={handleZoomChanged}
...
</GoogleMap>

我收到一个错误消息:无法读取 null 的属性“getZoom”,并警告无法为函数组件提供参考。我该如何解决这个问题?谢谢!

4

1 回答 1

0

我参考了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;

于 2020-10-29T23:58:39.797 回答