将函数提取到 react-leaflet 中的独立自定义 React 组件

Extract function to standalone custom React component in react-leaflet

我的主要目标是在初始加载 react-leaflet 中呈现 FeatureGroup 时调用 fitBounds。

这会正确呈现 -

<Map>
  <LayersControl>
    {getLayers(groups)}
  </LayersControl>
</Map>


function getLayers(featureGroups: MyFeatureGroup[]){
  const showOnLoad = true;
  return featureGroups.map((group: MyFeatureGroup) => {
    const groupRef = createRef<FeatureGroup>();
    const { id, name, } = group;
    return (
      <LayersControl.Overlay checked={showOnLoad} key={id} name={name}>
        <FeatureGroup ref={groupRef}>
          <Layer {...group} />
        </FeatureGroup>
      </LayersControl.Overlay>
    );
  });
}

但是,因为它使用的是函数而不是 React 组件,所以我无法使用 React hooks。

我尝试过的替代方案不起作用,即使它是包含在 React 组件中的相同代码 -

...same as above...

  return featureGroups.map((group: MyFeatureGroup) => (
    <ControlledGroup {...group} showOnLoad={showOnLoad} /> ///----- > ADDED THIS HERE
  ));


const ControlledGroup: React.FC<ControlledGroupProps> = (props) => {
  const groupRef = createRef<FeatureGroup>();
  const { map } = useLeaflet();
  /// -----> map is correctly defined here - injecting to all of the layers (LayersControl, FeatureGroup) does not solve the problem 
  const { showOnLoad, ...group } = props;
  useEffect(() => fitBounds(map, groupRef));  ///-----> Primary Goal of what I am trying to accomplish
  return (
    <LayersControl.Overlay
      checked={showOnLoad}
      key={group.id}
      name={name}
    >
      <FeatureGroup ref={groupRef}>
        <Layer map={map} {...group} />
      </FeatureGroup>
    </LayersControl.Overlay>
  );
};

我有点难过,因为这是相同的代码。在这两种情况下,getLayers 函数 return 都是 ReactNode。但是,当移动到独立的 ControlledGroup 组件时,它会在渲染时抛出错误 -

addOverlay is not a function

我尝试为 react-leaflet 创建自定义 class 组件,但我 运行 遇到的困难是 createLeafletElement return 是 Leaflet.Element,而我只是在寻找 return 个 ReactNode。也就是说,所有这些都是有效的 react-leaflet 组件。

我的问题 - 为什么一个有效而另一个无效? correct/recommended 将此函数转换为可渲染的独立 React 组件的方法是什么?

此外,如果有调用 fitBounds 的替代模式,那也会有所帮助。

如有任何见解,我们将不胜感激。

由于 LayersLayers.Overlay 共享继承,渲染错误的解决方案是将图层保持在一起并将功能组移动到独立组件。

这按预期工作并允许我在 groupRef -

上调用 useEffect
function getLayers(groups: MyFeatureGroup[]){
  return featureGroups.map((group: MyFeatureGroup) => {
    const { id, name, } = group;
   return (
///---> Keep the Overlay in the function here and extract just the FeatureGroup out
      <LayersControl.Overlay checked={showOnLoad} key={id} name={name}> 
        <ControlledGroup {...group}></ControlledGroup>
       </LayersControl.Overlay>
    );
}