Reactjs 单击按钮时,响应传单关闭弹出窗口

Reactjs 单击按钮时,响应传单关闭弹出窗口,reactjs,react-leaflet,Reactjs,React Leaflet,当我点击标记时,弹出窗口出现。弹出窗口有一个自定义的“关闭”按钮。我想用这个按钮代替右上角的默认“X” 我看到了这两个问题: popupRef.current.\u closeButton.click()不是一个选项,因为我想隐藏默认的关闭按钮-当我保留Popup属性closeButton={false} 当我点击我的按钮时,我得到一个错误TypeError:无法读取未定义的属性“closePopup” import React, {useRef} from 'react'; import

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

我看到了这两个问题:

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

当我点击我的按钮时,我得到一个错误
TypeError:无法读取未定义的属性“closePopup”

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;

我的推荐信有什么用得上的吗?

至少有两种方法:

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

第二次使用
popupElRef.current._close()通过引用您已经尝试实现的弹出元素<代码>元素
在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}
    >
...
const[map,setMap]=useState(null);
const popupElRef=useRef(null);
常量隐藏元素=()=>{
如果(!popupElRef.current | |!map)返回;
//popupElRef.current._close();
map.closePopup();
};
...
...

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}
    >
...