你可以尝试实现 React 组件:
export const Popup = ({ children, latitude, longitude, ...mapboxPopupProps }) => {
// this is a mapbox map instance, you can pass it via props
const { map } = useContext(MapboxContext);
const popupRef = useRef();
useEffect(() => {
const popup = new MapboxPopup(mapboxPopupProps)
.setLngLat([longitude, latitude])
.setDOMContent(popupRef.current)
.addTo(map);
return popup.remove;
}, [children, mapboxPopupProps, longitude, latitude]);
return (
/**
* This component has to have 2 divs.
* Because if you remove outter div, React has some difficulties
* with unmounting this component.
* Also `display: none` is solving that map does not jump when hovering
* ¯\_(ツ)_/¯
*/
<div style={{ display: 'none' }}>
<div ref={popupRef}>
{children}
</div>
</div>
);
};
经过一些测试,我意识到Popup
组件没有在地图上正确渲染。而且卸载组件也不成功。这就是为什么有两个 div 作为回报。但是,它可能只发生在我的环境中。
有关其他信息,请参阅https://docs.mapbox.com/mapbox-gl-js/api/#popupmapboxPopupProps
useEffect
依赖项确保 MapboxPopup 每次列表中的某些内容更改时都会重新创建并使用 return popup.remove;