【问题标题】:React leaflet close popup on button click单击按钮时反应传单关闭弹出窗口
【发布时间】:2021-05-29 08:05:41
【问题描述】:

当我单击标记时,会出现弹出窗口。弹出窗口有一个自定义的“关闭”按钮。我想用这个按钮代替右上角的默认“X”。

我看到了这两个问题: close popup react-leaflet after user click on button in popup
How can I make the Leaflet Popup to show when i click on a list button

popupRef.current._closeButton.click() 不是一个选项,因为我想隐藏默认关闭按钮 - 当我保留 Popup 属性 closeButton={false} 时它不起作用

当我点击我的按钮时,我收到一个错误TypeError: Cannot read property 'closePopup' of undefined

import React, {useRef} from 'react';
import {MapContainer, TileLayer, Marker, Popup} from 'react-leaflet';

const MyComponent = () => {

    const popupElRef = useRef(null);

    const hideElement = () => {
        popupElRef.current.leafletElement.closePopup();
    }

    return (
            <MapContainer
                ref={mapRef}
                <Marker>
                    <Popup ref={popupElRef} closeButton={false}>
                        <button onClick={hideElement}>Close popup</button>
                    </Popup>
                </Marker>
            </MapContainer>
    );
};

export default MyComponent;

当我使用console.log(popupElRef) 时,我看到一个没有leafletElement 方法的对象。我也没有看到任何与传单方法有关的东西。

options: {children: {…}}
_closeButton: a.leaflet-popup-close-button
_container: div.leaflet-popup.leaflet-zoom-animated
_containerBottom: -7
_containerLeft: -62
_containerWidth: 124
_contentNode: div.leaflet-popup-content
_events: {remove: Array(2)}
_initHooksCalled: true
_latlng: LatLng {lat: 50.50, lng: 15.67}
_leaflet_id: 1148
_map: NewClass {options: {…}, _handlers: Array(6), _layers: {…}, _zoomBoundLayers: {…}, _sizeChanged: false, …}
_mapToAdd: NewClass {options: {…}, _handlers: Array(6), _layers: {…}, _zoomBoundLayers: {…}, _sizeChanged: false, …}
_source: NewClass {options: {…}, _latlng: LatLng, _initHooksCalled: true, _popup: NewClass, _events: {…}, …}
_tip: div.leaflet-popup-tip
_tipContainer: div.leaflet-popup-tip-container
_wrapper: div.leaflet-popup-content-wrapper
_zoomAnimated: true
__proto__: NewClass

我的参考资料有什么办法吗?

【问题讨论】:

    标签: reactjs react-leaflet


    【解决方案1】:

    您至少有两种方法可以做到这一点:

    首先通过引用地图实例source来使用map.closePopup()

    第二次使用popupElRef.current._close();,方法是引用您已经尝试实现的弹出元素。 leafletElement 我认为在 3.x 版中已弃用,仅在 2.x 版中使用。

    const [map, setMap] = useState(null);
    const popupElRef = useRef(null);
    
    const hideElement = () => {
        if (!popupElRef.current || !map) return;
        // popupElRef.current._close();
        map.closePopup();
    };
    ...
    <MapContainer
          center={position}
          zoom={13}
          style={{ height: "100vh" }}
          whenCreated={setMap}
        >
    ...
    

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-23
      • 2016-09-10
      • 2018-05-22
      • 1970-01-01
      相关资源
      最近更新 更多