简单的问题,我正在使用
Polygons
动态渲染react-leaflet
。
多边形按预期显示。但是,我附加到
eventHandlers
的任何内容都不起作用。
const highlightFeature = (e) => {
console.log(e);
let layer = e.target;
layer.setStyle({
color: "black",
fillColor: "black"
});
};
let indents = [];
lightRailStop.features.map((feature, index) => {
indents.push(
<Polygon
positions={feature.geometry.coordinates}
clickable={true}
color={"red"}
stroke={false}
fillOpacity={0.45}
// This is not working!
eventHandlers={{
mouseover: highlightFeature,
click: () => {
console.log("marker clicked");
}
}}
/>
);
});
为什么会这样,我该如何解决?
完整小提琴: https://codesandbox.io/s/scratchpad-without-geojson-b8jsp5
您发布的沙箱正在使用
react-leaflet
版本 2。版本 2 处理事件的方式不同。 一个简单的 onClick
道具就可以了。 对于其他处理程序,您可以使用 onMouseEnter
或 onMouseOut
:
<Polygon
key={index}
positions={feature.geometry.coordinates}
onClick={() => console.log("this works")}
onMouseenter={highlightFeature}
onMouseut={(e) => console.log(e)}
/>
我确实建议更新到react-leaflet v3。
根据react传单的文档使用eventHandlers: https://react-leaflet.js.org/docs/api-components/#polygon
请参阅下面的代码:
<Polygon
pathOptions={location.colorIdentifier}
positions={location.coords}
eventHandlers={{
click: () => {
console.log('this works')
},
}}
></Polygon>