如何在根目录中引用 LeafletMap?

How to reference LeafletMap in the root?

我想从版本 2.8.0 迁移到 3.0.5。 API 在某种程度上发生了变化,不再导出 Map 元素,取而代之的是 MapContainer,它通过上下文 API 提供对其某些属性的引用.到目前为止,一切都很好。但我有一个简单的问题,我不能再在根元素中引用 LeafletMap 对象本身。在我有这个之前:

render(
  <Map center={position} zoom={13} ref={map}>
    <TileLayer
      attribution='&copy; <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='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
      </MapContainer>
    )

map 现在未定义。如何在我的根元素中引用地图?

使用 MapContainerwhenCreated 属性和 map 本地状态变量在创建地图时提取地图引用。它将触发 setMap 并保存地图实例。用这种方法记录了 here and here is an example

const [map, setMap] = useState(null);

<MapContainer center={position} zoom={13} whenCreated={setMap}>
     <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
</MapContainer>