You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将TypeScript定义文件(.d.ts)转换为JavaScript文件?

问题与解决方案

一、将.d.ts文件转换为JavaScript代码

你提供的.d.ts是TypeScript类型声明文件,仅定义类型结构,没有实际运行逻辑。要转换成可执行的JavaScript,需要补充组件的实现逻辑。结合MapConsumer的常见用途(作为Leaflet地图上下文的消费者),以下是对应的JavaScript实现:

import React from 'react';
import { MapContext } from 'react-leaflet';

export function MapConsumer({ children }) {
  return <MapContext.Consumer>{children}</MapContext.Consumer>;
}

说明:

  • .d.ts中声明的MapConsumerProps在JS中无需显式定义,直接解构接收children即可
  • 实现依赖react-leaflet内置的MapContext,用于传递Leaflet地图实例

二、Gatsby 2中Leaflet MapConsumer替代方案

新版react-leaflet已废弃MapConsumer,推荐使用useMap钩子或MapContainer的whenCreated属性来获取地图实例,以下是两种替代写法:

方案1:使用useMap钩子(函数组件场景)

import { useMap } from 'react-leaflet';
import { useRef, useEffect } from 'react';

function MapController({ sights, mapIsVisible }) {
  const map = useMap();
  const mapRef = useRef();
  const fitBoundCalled = useRef(null);

  useEffect(() => {
    if (!map) return;
    
    mapRef.current = map;

    if (fitBoundCalled.current == null) {
      map.fitBounds(sights.map(sight => [sight.node.frontmatter.lat, sight.node.frontmatter.long]));
      fitBoundCalled.current = false;
    }
  }, [map, sights]);

  useEffect(() => {
    if (!map) return;
    
    mapIsVisible ? map.dragging.enable() : map.dragging.disable();
  }, [map, mapIsVisible]);

  return null;
}

// 在MapContainer中引入使用
<MapContainer>
  <MapController sights={sights} mapIsVisible={mapIsVisible} />
  <TileLayer/>
  <Marker/>
</MapContainer>

方案2:使用MapContainer的whenCreated属性

import { useRef, useEffect } from 'react';

function MapComponent({ sights, mapIsVisible }) {
  const mapRef = useRef();
  const fitBoundCalled = useRef(null);

  const handleMapCreated = (map) => {
    mapRef.current = map;

    if (fitBoundCalled.current == null) {
      map.fitBounds(sights.map(sight => [sight.node.frontmatter.lat, sight.node.frontmatter.long]));
      fitBoundCalled.current = false;
    }
  };

  useEffect(() => {
    const map = mapRef.current;
    if (!map) return;
    
    mapIsVisible ? map.dragging.enable() : map.dragging.disable();
  }, [mapIsVisible]);

  return (
    <MapContainer whenCreated={handleMapCreated}>
      <TileLayer/>
      <Marker/>
    </MapContainer>
  );
}

说明:

  • 两种方案均可替代MapConsumer实现地图实例的获取与操作
  • useMap更适合在独立子组件中获取地图,whenCreated则直接在地图初始化时获取实例

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 18:05:16