Skip to content

Commit

Permalink
feat(map): 支持通过 ref 获取地图实例
Browse files Browse the repository at this point in the history
  • Loading branch information
wangxingkang committed Aug 30, 2022
1 parent 9847dfc commit 4cff4b6
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/map/map.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as Mapbox from 'mapbox-gl';
import { useEffect, useRef, useState } from 'react';
import { forwardRef, useEffect, useRef, useState, useImperativeHandle } from 'react';
import { useBoolean } from '@pansy/react-hooks';
import { getTargetElement } from '@pansy/shared/react';
import MapboxWorker from 'mapbox-gl/dist/mapbox-gl-csp-worker';
Expand All @@ -11,20 +11,21 @@ import { allProps, mapEventMap } from './config';

import 'mapbox-gl/dist/mapbox-gl.css';

import type { FC } from 'react';
import type { MapboxOptions } from 'mapbox-gl';
import type { MapProps, EventMapping } from './types';

// @ts-ignore
Mapbox.workerClass = MapboxWorker;

export const Map: FC<MapProps> = (props) => {
export const Map = forwardRef<Mapbox.Map, MapProps>((props, ref) => {
const containerRef = useRef<HTMLDivElement>(null);
const [ready, readyAction] = useBoolean(false);
const [ready, readyAction] = useBoolean();
const [map, setMap] = useState<Mapbox.Map>();

useEvents<Mapbox.Map, EventMapping>(map as Mapbox.Map, mapEventMap, props);

useImperativeHandle(ref, () => map as Mapbox.Map, [map]);

useEffect(() => {
const container = getTargetElement(containerRef);

Expand Down Expand Up @@ -70,7 +71,7 @@ export const Map: FC<MapProps> = (props) => {
</div>
</MapContext.Provider>
);
};
});

Map.defaultProps = {
attributionControl: false,
Expand Down

0 comments on commit 4cff4b6

Please sign in to comment.