reactjs 如何防止React-Leaflet Map的子节点上的事件冒泡

cgyqldqp  于 2023-04-20  发布在  React
关注(0)|答案(2)|浏览(368)

我有一个React-LeafletMap,我在里面渲染了一个div
出于某种原因,与div的内容交互会导致下面的Map响应(例如:双击将缩放Map,拖动将平移Map)-即使我在附加到div的处理程序中调用e.stopPropagation()
据我所知,调用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'));
4nkexdtk

4nkexdtk1#

对于瓣叶图,使用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元素传播到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>
  );
}
qyyhg6bp

qyyhg6bp2#

对于使用react-leaflet的更新版本的用户(例如:^4.2.1),我只能让它与react-leaflet-custom-control一起工作

{/* import Control from "react-leaflet-custom-control"; */}
<Control position="topright">
  <div
    ref={(ref) => {
      if (!ref) return;
      /** import L from "leaflet"; */
      L.DomEvent.disableClickPropagation(ref).disableScrollPropagation(ref);
    }}
  >
    <button onClick={() => console.log('Clicked')}>Click me</button>
  </div>
</Control>

Codesandbox

相关问题