UNPKG

@pansy/react-mapbox-gl

Version:

🌍 基于 Mapbox GL 封装的 React 组件库

52 lines (51 loc) 1.59 kB
// src/components/Source/source.tsx import React, { useEffect, useState, useRef, useMemo, cloneElement } from "react"; import { useMap } from "../../hooks/useMap"; import { isStyleLoaded } from "../../utils/isStyleLoaded"; import { updateSource, createSource } from "./utils"; var sourceCounter = 0; function Source(props) { const { map } = useMap(); const propsRef = useRef(props); const [, setStyleLoaded] = useState(0); const id = useMemo(() => props.id || `jsx-source-${sourceCounter++}`, []); useEffect(() => { if (map) { const forceUpdate = () => setTimeout(() => setStyleLoaded((version) => version + 1), 0); map.on("styledata", forceUpdate); forceUpdate(); return () => { var _a; map.off("styledata", forceUpdate); if (map.getStyle() && isStyleLoaded(map) && map.getSource(id)) { const allLayers = (_a = map.getStyle()) == null ? void 0 : _a.layers; if (allLayers) { for (const layer of allLayers) { if (layer.source === id) { map.removeLayer(layer.id); } } } map.removeSource(id); } }; } return void 0; }, [map]); let source = map && map.getStyle() && map.getSource(id); if (source) { updateSource(source, props, propsRef.current); } else { source = createSource(map, id, props); } propsRef.current = props; return source && React.Children.map( props.children, (child) => child && cloneElement(child, { source: id }) ) || null; } export { Source };