如何防止事件在React-Leaflet Map的子级上冒泡

时间:2019-07-12 01:45:18

标签: javascript reactjs dom leaflet react-leaflet

我有一个React-Leaflet地图,正在内部绘制div

由于某种原因,与div的内容进行交互会导致下方的地图做出响应(例如:双击将缩放地图,拖动将平移地图)-即使我在其中调用e.stopPropagation()附加到div的处理程序。

据我了解,调用stopPropagation()应该可以防止DOM事件到达地图本身。

为什么似乎stopPropagation()被忽略了?

我如何在地图内渲染div ,而使其事件不会冒泡到地图本身?

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'));

1 个答案:

答案 0 :(得分:1)

对于传单地图,请使用L.DomEvent.disableClickPropagation代替

  

stopPropagation添加到元素的'click''doubleclick',   'mousedown''touchstart'事件。

示例

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>
  );
}

Updated codepen

替代选项

阻止div元素传播到地图事件的另一种方法是将div 放在外部:

<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>
  );
}