reactjs - 带有 React-leaflet version3 的传单地图上的自定义按钮
问题描述
我是 React 打字稿的新传单学习者。想要在地图上创建自定义按钮。单击按钮时,将出现一个弹出窗口。我看到了很多例子,但它们都是基于旧版本的,我也尝试创建自己的但没有运气。该文档也没有提供太多帮助。即使是功能性自定义控件组件对我的应用程序也非常有效。对此的任何帮助将不胜感激。这是我的代码,
自定义按钮
import React, { Component } from "react";
import { useMap } from "react-leaflet";
import L, { LeafletMouseEvent, Map } from "leaflet";
class Description extends React.Component<{props: any}> {
createButtonControl() {
const MapHelp = L.Control.extend({
onAdd: (map : Map) => {
const helpDiv = L.DomUtil.create("button", ""); //how to pass here the button name and
//other property ?
//a bit clueless how to add a click event listener to this button and then
// open a popup div on the map
}
});
return new MapHelp({ position: "bottomright" });
}
componentDidMount() {
const { map } = this.props as any;
const control = this.createButtonControl();
control.addTo(map);
}
render() {
return null;
}
}
function withMap(Component : any) {
return function WrappedComponent(props : any) {
const map = useMap();
return <Component {...props} map={map} />;
};
}
export default withMap(Description);
我想这样称呼它
<MapContainer
center={defaultPosition}
zoom={6}
zoomControl={false}
>
<Description />
<TileLayer
attribution="Map tiles by Carto, under CC BY 3.0. Data by OpenStreetMap, under ODbL."
url="https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png"
/>
<ZoomControl position={'topright'}/>
</MapContainer>
解决方案
你很近。坚持使用类组件,您只需要继续创建按钮实例。你可以使用一个道具Description
来确定你的按钮会说什么和做什么:
<Description
title={"My Button Title"}
markerPosition={[20.27, -157]}
description="This is a custom description!"
/>
在你的描述中createButtonControl
,你快到了。你只需要填写一点:
createButtonControl() {
const MapHelp = L.Control.extend({
onAdd: (map) => {
const helpDiv = L.DomUtil.create("button", "");
this.helpDiv = helpDiv;
// set the inner content from the props
helpDiv.innerHTML = this.props.title;
// add the event listener that will create a marker on the map
helpDiv.addEventListener("click", () => {
console.log(map.getCenter());
const marker = L.marker()
.setLatLng(this.props.markerPosition)
.bindPopup(this.props.description)
.addTo(map);
marker.openPopup();
});
// return the button div
return helpDiv;
}
});
return new MapHelp({ position: "bottomright" });
}
工作代码框
有一百万种方法可以改变这一点,但希望这会让你继续前进。
推荐阅读
- python-3.x - 如何计算 Python 列表元素中子字符串的实例?
- java - Java 程序因某些测试用例超时而失败
- python - 有没有一种简单的方法可以在对象级别上记忆(和刷新)Python 上的属性?
- flutter - 自 catalina 更新以来,颤振不打印/调试打印/记录和忽略断点
- excel-formula - 尝试从另一个单元格提供格式代码
- google-app-engine - 如何使用 API 密钥在 App Engine 上简单地保护 API?
- python - Sqlalchemy 覆盖关联表中的字段
- python - 如何使用硬盘驱动器上的本地文件实现?
- python - 如何从 Coinmarketcap 解析历史 BTC 数据?
- arrays - 如何创建可循环的已分配但长度为零的数组?