如何解决如何在根中引用 LeafletMap?
我想从版本 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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。