React 传单 - 如何使用 useLeaflet 添加自定义组件
React leaflet- how to add custom components with useLeaflet
我正在尝试为我的传单地图创建一个信息面板,如下所示:leaflet-info-control。
此外,我使用 react 和 react-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] ? '–' + grades[i + 1] + '<br>' : '+')
}
</React.Fragment>
)
)
}
)
}
</div>
);
}
export default MapInfoControl;
您将执行与不使用 hook 时完全相同的操作,但有 3 个主要区别:
- 创建功能组件而不是基于 class 的组件
- 使用
useEffect
钩子代替 componentDidMount
- 使用
useLeaflet
钩子访问地图对象而不是HOCwithLeaflet
这里是 demo 一个活生生的例子。
我用了Leaflet官方文档提供的例子来演示
我正在尝试为我的传单地图创建一个信息面板,如下所示:leaflet-info-control。
此外,我使用 react 和 react-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] ? '–' + grades[i + 1] + '<br>' : '+')
}
</React.Fragment>
)
)
}
)
}
</div>
);
}
export default MapInfoControl;
您将执行与不使用 hook 时完全相同的操作,但有 3 个主要区别:
- 创建功能组件而不是基于 class 的组件
- 使用
useEffect
钩子代替componentDidMount
- 使用
useLeaflet
钩子访问地图对象而不是HOCwithLeaflet
这里是 demo 一个活生生的例子。
我用了Leaflet官方文档提供的例子来演示