gpt4 book ai didi

react-leaflet - 使用 TypeScript 的 react-leaflet 中的 mapbox-gl-leaflet?

转载 作者:行者123 更新时间:2023-12-05 03:02:20 28 4
gpt4 key购买 nike

我正在尝试在 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);

但是我得到以下错误:

Property 'mapboxGL' does not exist on type 'typeof import("c:/Users/.../node_modules/@types/leaflet/index")'.ts(2339)

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

最佳答案

解决此错误 type definitions for mapbox-gl-leaflet需要安装,例如:

npm install --save @types/mapbox-gl-leaflet

最后但同样重要的是,react-leaflet type definitions目前react-leaflet v2完全兼容,需要进行一些额外的调整。由于当前版本 @types/react-leafletreact-leaflet v1 为目标,缺少版本 2 中的一些类型定义(有关更多详细信息,请参阅 this thread),例如 withLeaflet HOC。好消息是 PR 添加对版本 2 的支持已提交(但尚未批准)

无论如何,可以这样声明缺少的 withLeaflet 类型 def:

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);

Here is a demo

关于react-leaflet - 使用 TypeScript 的 react-leaflet 中的 mapbox-gl-leaflet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54898616/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com