如何在React传单中有条件地设置CircleMarkers的样式



所以,和其他一些用户一样,我最近遇到了在React传单GeoJSON层的弹出窗口中添加React功能的问题。在阅读了SO上的几篇文章后,问题显然归结为使用本机传单功能与React传单实现抽象出的功能之间的不匹配。在使用原生的Leaflet方法时,弹出绑定只接受一个字符串,这会阻止添加JSX或其他交互。

在放弃GeoJSON组件的过程中,我也失去了onEachFeature函数,这是轻松地为层设置样式和添加事件的主要方法。在重构我的应用程序以使用Circle标记时,我似乎不知道如何根据功能的属性有条件地设置单个标记的样式。GeoJSON LayerpathOptions道具似乎不接受这样的函数:

import { CircleMarker, Popup } from "react-leaflet";
import PopupContent from "./PopupContent";
const CircleMarkerLayer = ({ data }) => {
return  data.features.map((feature) => {
const { coordinates } = feature.geometry
const markerStyles = function(feature) {
switch (feature.properties.type) {
case 'Sticker': return {color: '#a50026'};
case 'Mural':   return {color: '#d73027'};
case 'Marker':   return {color: '#f46d43'};
case 'Characters':   return {color: '#fdae61'};
case 'Letters':   return {color: '#fee090' };
case 'Tippex':   return {color: '#ffffbf'};
case 'Spray':    return {color: '#e0f3f8'};
case 'Chalk':    return{color: '#abd9e9'};
case 'Label maker sticker':    return{color: '#74add1' };
case 'Poster':    return{color: '#4575b4'};
}
}
return (
<CircleMarker key={feature.properties.id} center={[coordinates[1], coordinates[0]]} pathOptions={markerStyles}>
<Popup>
<PopupContent content={feature} />
</Popup>
</CircleMarker>
)
}
)
}

此外,还不清楚如何添加其他事件,如MouseOver和MouseOut,我想将它们用作UI的一部分。我的最终目标是在弹出窗口中的图像中添加一个LightBox,但目前我对条件样式感到困惑。

CircleMarker仍然可以采用pathOptions,其类型应该是:

export interface PathOptions extends InteractiveLayerOptions {
stroke?: boolean | undefined;
color?: string | undefined;
weight?: number | undefined;
opacity?: number | undefined;
lineCap?: LineCapShape | undefined;
lineJoin?: LineJoinShape | undefined;
dashArray?: string | number[] | undefined;
dashOffset?: string | undefined;
fill?: boolean | undefined;
fillColor?: string | undefined;
fillOpacity?: number | undefined;
fillRule?: FillRule | undefined;
renderer?: Renderer | undefined;
className?: string | undefined;
}

因此,在这种情况下,只需使用您已经拥有的功能:

import { CircleMarker, Popup } from "react-leaflet";
import PopupContent from "./PopupContent";
const markerStyles = (feature) => {
switch (feature.properties.type) {
case "Sticker":
return { color: "#a50026" };
case "Mural":
return { color: "#d73027" };
case "Marker":
return { color: "#f46d43" };
case "Characters":
return { color: "#fdae61" };
case "Letters":
return { color: "#fee090" };
case "Tippex":
return { color: "#ffffbf" };
case "Spray":
return { color: "#e0f3f8" };
case "Chalk":
return { color: "#abd9e9" };
case "Label maker sticker":
return { color: "#74add1" };
case "Poster":
return { color: "#4575b4" };
}
};
const CircleMarkerLayer = ({ data }) => {
return data.features.map((feature) => {
const { coordinates } = feature.geometry;
return (
<CircleMarker
key={feature.properties.id}
center={[coordinates[1], coordinates[0]]}
pathOptions={markerStyles(feature)}
>
<Popup>
<PopupContent content={feature} />
</Popup>
</CircleMarker>
);
});
};

最新更新