MapboxGLjs React ref hook 的 TypeScript 类型

TypeScript type for MapboxGLjs React ref hook

我正在尝试为我正在使用钩子和 TypeScript 在 React 中编写的 mapboxgl 地图添加源。

export default function App() {
  const mapContainer = React.useRef<any>(null);
   const map = React.useRef<any>(null);
   const [lng, setLng] = React.useState(-74.0632);
   const [lat, setLat] = React.useState(40.7346); 
   const [zoom, setZoom] = React.useState(12);

  React.useEffect(() => {
    if (map.current) return; // initialize map only once
    map.current = new mapboxgl.Map({
      container: mapContainer.current,
      style: 'mapbox://styles/mapbox/streets-v11',
      center: [lng, lat],
      zoom: zoom
    });
    map.addSource('property-data', {
      type: 'geojson',
      data: 'path/to/data.geojson'
    });
    
  });

我遇到了以下错误:

Property 'addSource' does not exist on type 'MutableRefObject'

没有的话应该用什么类型?

您想在 ref 中保留一个 mapboxgl.Map,并且您还希望它在初始化之前为 null。所以这意味着你的参考类型是:

const map = React.useRef<mapboxgl.Map | null>(null);

这很好解决(最好消除对 any 的所有使用),但这与您遇到的错误无关。

当你有一个 ref 时,你 总是 通过 current 属性 访问它所引用的内容。因此,您只需要将最后一行更改为:

map.current.addSource(/* ... */)

Working example playground