For that matter a webpack feature called dynamic require could be utilized, for example with expression :
(为此,可以使用称为动态需求的webpack功能,例如,带有expression :)
const icon = L.icon({
iconUrl: require(`../public/custom-icons/${item.iconName}`),
});
icons images dynamically get loaded from /public/custom-icons/
folder and included in bundle
(图标图像从/public/custom-icons/
文件夹动态加载并包含在捆绑包中)
Example
(例)
const MapExample = () => {
const data = [
{ position: { lat: -33.8478796, lng: 150.7918932 }, title: "Sydney", "iconName" : "leaf-red.png" },
{ position: { lat: -31.954654, lng: 115.8399823 }, title: "Perth ", "iconName" : "leaf-green.png" }
];
return (
<Map center={{ lat: -24.9929159, lng: 115.2297986 }} zoom={4}>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
{data.map((item, idx) => {
const icon = L.icon({
iconUrl: require(`../public/custom-icons/${item.iconName}`),
iconSize: [24, 36],
iconAnchor: [12, 36],
popupAnchor: [0, -25]
});
return (
<Marker key={idx} icon={icon} position={item.position}>
<Popup>{item.title}</Popup>
</Marker>
);
})}
</Map>
);
};
Here is a demo
(这是一个演示)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…