【问题标题】:TypeScript type for MapboxGLjs React ref hookMapboxGLjs React ref hook 的 TypeScript 类型
【发布时间】:2021-09-22 21:23:08
【问题描述】:

我正在尝试为我在 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”

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

【问题讨论】:

    标签: reactjs typescript mapbox-gl-js


    【解决方案1】:

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

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

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

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

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

    Working example playground

    【讨论】:

    • Alex 又来救我了。我在发布后不久就发现了那个“当前”错误。 ? 再次感谢您的帮助,Alex!
    猜你喜欢
    • 2021-08-03
    • 2019-05-08
    • 2022-07-27
    • 1970-01-01
    • 2019-08-27
    • 2021-06-17
    • 2021-03-22
    • 1970-01-01
    • 2021-06-28
    相关资源
    最近更新 更多