当我单击标记时,会出现弹出窗口。弹出窗口有一个自定义的“关闭”按钮。我想使用这个按钮而不是右上角的默认“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
Table Panel
不是一个选项,因为我想隐藏默认关闭按钮 - 当我保留弹出属性 popupRef.current._closeButton.click()
当我点击按钮时出现错误 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
有什么办法可以让我的参考文献起作用吗?
答案 0 :(得分:0)
您至少有两种方法可以做到这一点:
首先通过引用地图实例 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}
>
...