用户单击弹出窗口中的按钮后关闭弹出窗口 react-leaflet

IT技术 reactjs popup leaflet react-leaflet
2021-05-14 00:48:43

所以基本上想为 react-leaflet Popup 组件定制关闭,接缝这与原生 API 传单无关,但使用 react-leaflet 的 react 组件我找不到解决方案。

3个回答

目前,我发现关闭弹出窗口的唯一方法如下:

constructor(props){
    super(props);
    this.popup = React.createRef();
}

// the magic
closePopusOnClick(){
    this.popup.current.leafletElement.options.leaflet.map.closePopup();
}

render(){
    return <Marker position={[this.props.lat, this.props.lng]}>
        <Popup ref={this.popup}>
            <Button onClick={this.closePopusOnClick}>Close popup</Button>
        </Popup>
    </Marker>;
}

希望能帮助到你!

"react-leaflet": "^3.0.2"我设法关闭弹出窗口:

popupRef.current._closeButton.click()

Popup.close()必须开箱即用但可以完成工作的未来方法相比不是很好......

我最终得到了与Luca's Answer类似的解决方案,所以我想我也将其添加为答案。我需要在移动或缩放地图时关闭所有弹出窗口,结果如下:

import React, { useRef } from "react";
import { Map } from "react-leaflet"

export default () => {
  const mapRef = useRef(null);

  const closePopups = () => {
    mapRef.current.leafletElement.closePopup();
  };

  const handleOnDragend = e => {
    closePopups();
  };

  const handleOnZoomend = e => {
    closePopups();
  };

  if (typeof window === 'undefined') {
    return null;
  }

  return (
      <Map
        ref={mapRef}
        onDragend={handleOnDragend}
        onZoomend={handleOnZoomend}
      >
      </Map>
  )
}

但是,这可以扩展,以便任何东西都可以调用该closePopups方法。