首页 > 解决方案 > MapboxGLjs React ref hook 的 TypeScript 类型

问题描述

我正在尝试为我在 React 中使用钩子和 TypeScript 编写的 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'
    });
    
  });

我遇到以下错误:

“MutableRefObject”类型上不存在属性“addSource”

如果没有,我应该使用什么类型?

标签: reactjstypescriptmapbox-gl-js

解决方案


您希望将 a 保留mapboxgl.Map在 ref 中,并且您还希望它null在初始化之前存在。这意味着您的参考类型是:

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

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

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

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

工作示例游乐场


推荐阅读