在React-Leaflet中使用TypeScript的Mapbox-GL-Leaflet?

3

我想要实现这个描述在 Render mapbox vector tiles inside react-leaflet? 的实现,但是我使用的是 TypeScript。

所以我的文件看起来像这样:

import * as L from "leaflet";
import {} from "mapbox-gl-leaflet";
import * as PropTypes from "prop-types";
import { GridLayer, withLeaflet } from "react-leaflet";

class MapBoxGLLayer extends GridLayer {
  createLeafletElement(props) {
    return L.mapboxGL(props);
  }
}

/*
* Props are the options supported by Mapbox Map object
* Find options here:https://www.mapbox.com/mapbox-gl-js/api/#new-mapboxgl-map-options-
*/
MapBoxGLLayer.propTypes = {
  accessToken: PropTypes.string.isRequired,
  style: PropTypes.string
};

MapBoxGLLayer.defaultProps = {
  style: "mapbox://styles/mapbox/streets-v9"
};

export default withLeaflet(MapBoxGLLayer);

但是我收到以下错误:

在'typeof import("c:/Users/.../node_modules/@types/leaflet/index")'类型上不存在属性'mapboxGL'.ts(2339)

因此leaflet没有mapboxGL的定义(这很有道理,因为mapboxGL不是它的一部分) - 但是我如何创建或引用一个mapboxGL的定义,以便我可以调用L.mapboxGL(props)?

1个回答

4
为了解决这个错误,需要安装mapbox-gl-leaflet的类型定义,例如:
npm install --save @types/mapbox-gl-leaflet

最后但并非最不重要的是,react-leaflet类型定义目前与react-leaflet v2不完全兼容,需要进行一些额外的调整。由于@types/react-leaflet当前版本针对的是react-leaflet v1,因此缺少了一些来自版本2的类型定义(参见this thread以获取更多详细信息),例如withLeaflet HOC。好消息是已经提交了一个PR,增加了对版本2的支持(但尚未获得批准)。
无论如何,缺失的withLeaflet类型定义可以这样声明:
declare module "react-leaflet" {
  const withLeaflet: <T>(component: T) => T;
}

最后,组件可以像这样实现:
import * as L from "leaflet";
import "mapbox-gl-leaflet";

declare module "react-leaflet" {
  const withLeaflet: <T>(component: T) => T;
}


import {Children, MapLayer, withLeaflet} from "react-leaflet";


export interface IMapboxGLProps extends L.MapboxGLOptions {
  children?: Children;
}


class MapBoxGLLayer extends MapLayer<IMapboxGLProps,{}> {

  public static defaultProps = {
    style: "mapbox://styles/mapbox/streets-v9"
  };

  public createLeafletElement(props:IMapboxGLProps)  {
    return L.mapboxGL(props);
  }

  public render() {
    return null
  }
}

export default withLeaflet(MapBoxGLLayer);

这里有一个演示


1
精彩的回答!非常感谢! - BruceM
1
完美!谢谢! - Stanislav Glushak
1
非常感谢!我忘记导入“mapbox-gl-leaflet”; - Cowas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接