React Leaflet:如何在首次渲染后访问 Map 对象?

问题描述 投票:0回答:1

我有一个带有两个子组件的父组件:

  1. 传单地图
  2. 地图上可见的位置列表(使用地图的 getBounds() 计算)

我在初始化位置列表时遇到问题。我尝试过的一些事情:

  • 我在两个组件的父组件中使用
    useRef
    创建一个引用,并通过
    ref
    标签将其传递给 MapContainer,但在父组件的 useEffect 发生时它尚未初始化。
  • 我创建了一个回调,尝试在
    whenReady
    中调用该回调以将边界传递回父级,但是
    whenReady
    无权访问地图对象。
  • 我创建了
    MapContainer
    的子级来处理事件。该子项对
    'load'
    'moveend'
    做出反应,这适用于地图移动但在第一次渲染时不运行的情况。
  • 我尝试让事件处理程序组件在父级中调用回调来触发重绘。但这会导致组件更新期间组件更新,这是不允许的。

那么如何在加载完成后在父级中触发具有地图边界的回调?

leaflet react-leaflet
1个回答
0
投票

当使用 React leaflet 时,我认为创建可以放置在 MapContainer 中的组件更容易,这些组件可以处理特定的任务,例如界限

这是我获取地图边界的方法:

const Bounds: React.FC<{ onMove: (bounds: MapBounds) => void }> = ({
  onMove,
}) => {
  const map = useMapEvent("moveend", (event) => {
    onMove(convertBounds(event.sourceTarget.getBounds()));
  });

  const convertBounds = (bounds: any) => {
    const southWest = bounds.getSouthWest();
    const northEast = bounds.getNorthEast();

    return {
      min: {
        lat: southWest.lat,
        lng: southWest.lng,
      },
      max: {
        lat: northEast.lat,
        lng: northEast.lng,
      },
    };
  };

  // set inital bounds, important that onMove is not changed because that wil cause loop
  useEffect(() => {
    onMove(convertBounds(map.getBounds()));
  }, [onMove, map]);

  return <></>;
};

然后您可以将

<Bounds onMove={onBoundsChange} />
作为子项添加到 MapContainer。

© www.soinside.com 2019 - 2024. All rights reserved.