我尝试使用函数组件加载传单地图,但收到错误消息“未找到地图容器”。我找到了一个将 <div id="map">
添加到 DOM 的解决方案。我找不到在函数组件中执行此操作的方法。我最终使用类组件来做到这一点,它的工作原理:
import React from "react";
import L, { LeafletMouseEvent } from "leaflet";
import "leaflet/dist/leaflet.css";
import icon from "leaflet/dist/images/marker-icon.png";
import iconShadow from "leaflet/dist/images/marker-shadow.png";
let DefaultIcon = L.icon({
iconUrl: icon,
shadowUrl: iconShadow,
});
class LeafletMap extends React.Component {
componentDidMount() {
this.map();
}
map() {
L.Marker.prototype.options.icon = DefaultIcon;
var mapSW = new L.Point(0, 960),
mapNE = new L.Point(960, 0);
var map = L.map("map", { crs: L.CRS.Simple }).setView([0, 0], 4);
L.tileLayer("/assets/maps/map0/{z}/{x}/{y}.png", {
tileSize: 32,
minZoom: 4,
maxZoom: 5,
noWrap: true,
}).addTo(map);
var maxBounds = L.latLngBounds(
map.unproject(mapSW, map.getMaxZoom()),
map.unproject(mapNE, map.getMaxZoom())
);
map.setMaxBounds(maxBounds);
var marker = L.marker([0, 0], {
draggable: true,
}).addTo(map);
marker.bindPopup("<b>Our hero!</b>").openPopup();
function onMapClick(e: LeafletMouseEvent) {
let tileSize = new L.Point(32, 32);
let pixelPoint = map.project(e.latlng, map.getMaxZoom()).floor();
let coords = pixelPoint.unscaleBy(tileSize).floor()
alert("You clicked the map at " + coords);
}
map.on("click", onMapClick);
}
render() {
return <div id="map"></div>;
}
}
export default LeafletMap;
这是 LeafletMap 组件被调用的地方:
const comp: React.FC<RouteComponentProps> = () => {
return (
<div>
<Grid columns={2}>
<Grid.Column>
<LeafletMap/>
</Grid.Column>
// codes
</Grid>
</div>
现在我需要使用钩子特性,所以我必须使用函数组件。如何解决“未找到地图容器”错误或使用函数组件向 DOM 添加地图元素?
答案 0 :(得分:2)
从您包含的代码来看,您似乎没有使用 react-leaflet
,而是使用原生传单代码。
将您的类组件用作函数应该不是问题。用效果钩子替换 componentDidMount
并移除渲染方法
export default function LeafletMap() {
useEffect(() => {
map();
}, []);
...rest of code same as yours only remove render method
return <div id="map" style={{ height: "100vh" }}></div>;
}
由于您使用的是打字稿,因此错误可能是由于类型错误所致。
我使用了一个 openstreet map tile provider(因为你使用的是自定义的)和一些固定的图标,它似乎工作没有错误