React 传单 - 如何使用 useLeaflet 添加自定义组件

React leaflet- how to add custom components with useLeaflet

我正在尝试为我的传单地图创建一个信息面板,如下所示:leaflet-info-control。 此外,我使用 reactreact-leaflet。为了访问全局传单地图对象,react-leaflet 提供了 useLeaflet() 钩子。

我的代码的问题是:我可以看到我的组件已渲染,但它实际上是在地图后面渲染的。如何在地图前添加 div to/in?

功能比较

import {useLeaflet} from "react-leaflet";
import React, {useEffect} from 'react';

function MapInfoControl({getColor}) {

    const leafletContext = useLeaflet();
    const grades = [95, 75, 50, 30, 25];

    useEffect(() => {
        console.log(leafletContext) // access the LeafletContext object.
    });

    return (
        <div className="legend">
            {
                grades.map((grade, i) => (
                        <React.Fragment key={i}>
                            <i className="legend-color-box" style={{background: getColor(grades[i])}}/>
                            {
                                grades[i] + (grades[i + 1] ? '&ndash;' + grades[i + 1] + '<br>' : '+')
                            }
                        </React.Fragment>
                    )
                )
            }
            )
            }
        </div>
    );
}

export default MapInfoControl;

您将执行与不使用 hook 时完全相同的操作,但有 3 个主要区别:

  1. 创建功能组件而不是基于 class 的组件
  2. 使用 useEffect 钩子代替 componentDidMount
  3. 使用useLeaflet钩子访问地图对象而不是HOCwithLeaflet

这里是 demo 一个活生生的例子。

我用了Leaflet官方文档提供的例子来演示