我有一个 React-Leaflet我在里面渲染一个 div
的 map 。
出于某种原因,与 div 的内容交互会导致下面的 map 做出响应(例如:双击会缩放 map ,拖动会平移 map )——即使我正在调用 e.stopPropagation ()
在附加到 div 的处理程序中。
据我所知,调用 stopPropagation()
应该可以防止 DOM 事件到达 map 本身。
为什么 stopPropagation()
似乎被忽略了?
如何在 map 内 渲染一个 div 而它的事件不会冒泡到 map 本身?
Here is an example codepen显示问题。
import { Map, TileLayer } from 'react-leaflet';
const MyMap = props => (
<Map zoom={13} center={[51.505, -0.09]}>
<TileLayer url={"http://{s}.tile.osm.org/{z}/{x}/{y}.png"} />
{/*
HOW do I get this div to NOT pass it's events down to the map?!?!
Why does e.stopPropagation() appear to not work?
*/}
<div
id="zone"
onClick={e => e.stopPropagation()}
onMouseDown={e => e.stopPropagation()}
onMouseUp={e => e.stopPropagation()}
>
<p>Double-click or click and drag inside this square</p>
<p>Why does the map zoom/pan?</p>
</div>
</Map>
);
ReactDOM.render(<MyMap />, document.getElementById('root'));
最佳答案
传单 map 使用 L.DomEvent.disableClickPropagation
而不是:
Adds
stopPropagation
to the element's'click'
,'doubleclick'
,'mousedown'
and'touchstart'
events.
例子
function MyMap() {
return (
<div>
<Map zoom={13} center={[51.505, -0.09]}>
<TileLayer url={"http://{s}.tile.osm.org/{z}/{x}/{y}.png"} />
<MyInfo />
</Map>
</div>
);
}
在哪里
function MyInfo() {
const divRef = useRef(null);
useEffect(() => {
L.DomEvent.disableClickPropagation(divRef.current);
});
return (
<div ref={divRef} id="zone">
<p>Double-click or click and drag inside this square</p>
<p>Why does the map zoom/pan?</p>
</div>
);
}
备选方案
另一种阻止 div 元素传播到 map 事件的方法是将 div 放在 map 元素的外部:
<div>
<Map zoom={13} center={[51.505, -0.09]}>
<TileLayer url={"http://{s}.tile.osm.org/{z}/{x}/{y}.png"} />
</Map>
<MyInfo />
</div>
在哪里
function MyInfo() {
return (
<div id="zone">
<p>Double-click or click and drag inside this square</p>
<p>Why does the map zoom/pan?</p>
</div>
);
}
关于javascript - 如何防止 React-Leaflet Map 子节点上的事件冒泡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56999231/