react-google-maps报错:未用withGoogleMap() HOC包裹组件,疑版本问题
解决react-google-maps中"Did you wrap component with withGoogleMap() HOC?"错误
这个错误提示其实已经把问题点得很清楚啦——你用的react-google-maps@9.4.5版本不允许直接渲染<GoogleMap>组件,必须通过它提供的withGoogleMap高阶组件(HOC)来包裹你的地图逻辑组件,这是这个版本库的强制使用规则,和你怀疑的版本兼容关系不大(你的React 16.4和这个版本的react-google-maps是兼容的)。
具体修改步骤
你需要调整代码结构,把<GoogleMap>放在被withGoogleMap包裹的组件里,同时还要指定地图容器的尺寸(否则地图会无法显示)。修改后的代码如下:
import React, { Component } from 'react'; // 别忘了导入withGoogleMap import { withGoogleMap, GoogleMap } from 'react-google-maps'; // 第一步:用withGoogleMap包裹包含GoogleMap的组件 const MyMap = withGoogleMap(() => ( <GoogleMap // 设置默认缩放级别和中心点,根据你的需求调整 defaultZoom={10} defaultCenter={{ lat: 39.9042, lng: 116.4074 }} /> )); class App extends Component { render() { return ( <div className="App"> {/* 第二步:渲染被HOC包裹后的组件,必须指定容器和地图元素的样式 */} <MyMap containerElement={<div style={{ height: '500px', width: '100%' }} />} mapElement={<div style={{ height: '100%' }} />} /> </div> ); } } export default App;
关键说明
withGoogleMap的作用是帮你处理Google Maps API的加载、初始化等底层逻辑,必须用它来包装包含<GoogleMap>的组件containerElement和mapElement是必填的,用来定义地图容器的尺寸和样式,没有这两个属性地图会无法正常显示- 如果后续需要添加标记(Marker)、信息窗口(InfoWindow)等组件,都要放在
withGoogleMap包裹的那个函数组件内部
额外建议
如果觉得这种HOC的使用方式比较繁琐,你可以考虑升级到@react-google-maps/api——这是react-google-maps的后续维护版本,使用方式更简洁(支持函数组件和hooks),兼容性也更好。不过就当前你的依赖版本来说,按照上面的代码修改就能解决问题啦。
内容的提问来源于stack exchange,提问作者SomethingsGottaGive
相关产品推荐
相关产品推荐

