问题描述
我想从版本 2.8.0 迁移到 3.0.5。 API 在某种程度上发生了变化,不再导出 Map
元素,而是通过 Context API 提供对其某些属性的引用的 MapContainer
。到现在为止还挺好。但是我遇到了一个简单的问题,我无法再在根元素中引用 LeafletMap 对象本身。在我有这个之前:
render(
<Map center={position} zoom={13} ref={map}>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</Map>
)
map
会给我对 LeafletMap 对象本身的引用。现在是 3.0.5 中的代码:
render(
<MapContainer center={position} zoom={13} ref={map}>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</MapContainer>
)
map
现在未定义。如何在我的根元素中引用地图?
解决方法
使用 whenCreated
的 MapContainer
属性和 map
局部状态变量在创建地图时提取地图参考。它将触发 setMap 并保存地图实例。它记录在 here 中,这里是使用这种方法的 example。
const [map,setMap] = useState(null);
<MapContainer center={position} zoom={13} whenCreated={setMap}>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</MapContainer>