我在我的React项目中使用传单v1.7.1和react-leaflet v3.0.5。
当我在React Router的“设置”文档页面中尝试设置示例时,标记图标会变成损坏的图像,如下图红色圆圈所示:
在React Router的文档中,标记应如下所示:
经检查,保存标记图像的标记的src
属性<img>
应为https://unpkg.com/[email protected]/dist/images/marker-icon-2x.png
。但是,经检查后,我<img>
的src
属性显示为乱码:
I suspect that I did something wrong when I tried to set-up Leaflet and React Leaflet via npm.
Alternatively, follow these steps to replicate the issue:
npx create-react-app leaflet-test
cd leaflet-test/
npm i leaflet react-leaflet
Open the project in code editor. Go to App.js
and use the following code:
import React from "react";
import "./App.css";
import "leaflet/dist/leaflet.css";
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
const styles = {
mapRoot: {
height: 400,
},
};
export default function App() {
return (
<MapContainer
style={styles.mapRoot}
center={[51.505, -0.09]}
zoom={13}
scrollWheelZoom={false}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={[51.505, -0.09]}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</MapContainer>
);
}
npm start
I'm not sure whether I've set-up Leaflet wrongly in React or it's a bug from Leaflet or React Leaflet. Thanks in advance!
For reference, this is due to webpack rewriting URL's in CSS, whereas Leaflet uses it to detect the paths to its icon images.
See the details in Leaflet issue #4968.
When using Leaflet through a CDN, the Leaflet CSS is not fiddled with, so it works correctly.
您仍然可以通过webpack使用它,但是您应该只使用自定义图标,或者显式告诉Leaflet在哪里可以找到其默认图标的图像:
import L from 'leaflet';
delete L.Icon.Default.prototype._getIconUrl;
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'),
});
我还专门为这种情况制作了一个插件:leaflet-defaulticon-compatibility
从CSS检索所有Leaflet Default Icon选项,尤其是所有图标图像URL的选项,以提高与在CSS中修改URL的捆绑器和框架的兼容性。
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';
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句