reactjs - React Leaflet v3:创建控件的好方法
问题描述
我在我的反应应用程序中显示带有反应传单 v3 的地图。
我只想添加一个自定义控件,但我不知道这样做的好方法是什么。
实际上,我就是这样做的,但它似乎不起作用。
function DptCtl(props) {
// Control
const map = useMap();
// List of dpts and provinces
const dpts = useSelector(dptsSelector);
L.Control.Dpts = L.Control.extend({
onAdd(map) {
const container = L.DomUtil.create('div');
const input = L.DomUtil.create('input', container);
return container;
},
onRemove(map) {}
})
L.Control.dpts = function (opts) {
return new L.Control.Dpts(opts);
}
useEffect(() => {
const control = L.Control.dpts({ position: props.position })
map.addControl(control)
return () => {
map.removeControl(control)
}
}, [dpts])
return null;
}
解决方案
React-Leaflet v3在核心 API中提供了createControlComponent Hook,它接收一个 Leaflet 控件的实例并返回一个 Leaflet 元素。
这是一个使用 Leaflet 的缩放控件的示例:
import L from 'leaflet';
import { createControlComponent } from '@react-leaflet/core';
const createControlLayer = (props) => {
// Set up an instance of the control:
const controlInstance = new L.Control.Zoom(props);
return controlInstance;
};
// Pass the control instance to the React-Leaflet createControlComponent hook:
const customControl = createControlComponent(createControlLayer);
export default customControl;
然后,将新的自定义控件层添加到地图:
<MapContainer
center={[37.0902, -95.7129]}
zoom={3}
zoomControl={false}
style={{ height: '100vh', width: '100%', padding: 0 }}
whenCreated={(map) => setMap(map)}
>
<CustomControl />
<LayersControl position="topright">
<LayersControl.BaseLayer checked name="Map">
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url={maps.base}
/>
</LayersControl.BaseLayer>
</LayersControl>
</MapContainer>
推荐阅读
- scala - sender() 导致 deadLetters 用于实现但不在单元测试中
- image - 如何让用户使用 Flutter 在此代码中输入图像?
- reactjs - 如何组合多个异步文件上传,并能够同时引用和写入两个新创建的 URL 到数据库?
- loops - Fortran 循环时嵌套 Do 和 Do
- mongodb - 如何提高应用性能?[更新]
- kotlin - Thymeleaf:一个简单的 for 循环中的“异常评估 OGNL 表达式”
- reactjs - 如何在 mongodb 中使用 editor.js
- django - Django:如何使用外键的特定字段加载查询集?
- c - 即使我在 C 编程中将最小值设置为 1,Rand() 仍然会生成 0
- java - 使用 apache poi 创建的 Excel 文档中的单元格边框问题