反应传单有一个破损的标记

react leaflet have a broken marker

我导入了 Leaflet 模块以及一些删除图标的代码。

import L from "leaflet";
import { Map, TileLayer, Marker, Popup } from "react-leaflet";
import "leaflet/dist/leaflet.css";

delete L.Icon.Default.prototype._getIconUrl;

L.Icon.Default.mergeOptions({
  iconRetinaUrl: require("./images/marker-icon-2x.png"),
  iconUrl: require("./images/marker-icon.png"),
  shadowUrl: require("./images/marker-shadow.png"),
});

标记图标位于我的图像文件夹中。 我也试过直接要求:

L.Icon.Default.mergeOptions({
  iconRetinaUrl: require("leaflet/dist/images/marker-icon-2x.png"),
  iconUrl: require("leaflet/dist/images/marker-icon.png"),
  shadowUrl: require("leaflet/dist/images/marker-shadow.png"),
});

但我的记号笔还是坏了。

如果您使用的是 create-react-app,这应该适用于 Webpack 配置。你必须把这段代码放在它会在你的 <Marker> 元素呈现之前执行的地方,就像在你的 App.tsx 文件的顶部:

import L from 'leaflet';
import markerIcon2x from 'leaflet/dist/images/marker-icon-2x.png';
import markerIcon from 'leaflet/dist/images/marker-icon.png';
import markerShadow from 'leaflet/dist/images/marker-shadow.png';

delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.mergeOptions({
    iconUrl: markerIcon,
    iconRetinaUrl: markerIcon2x,
    shadowUrl: markerShadow,
})

使用 leaflet-defaulticon-compatibility 插件,它应该可以在没有更多代码的情况下工作,前提是您的构建引擎配置已经设置为处理 CSS 中的 URL:

$ npm install leaflet-defaulticon-compatibility --save

import 'leaflet/dist/leaflet.css';
import 'leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.webpack.css'; // Re-uses images from ~leaflet package
import * as L from 'leaflet';
import 'leaflet-defaulticon-compatibility';

Disclaimer: I am the author of that plugin