使用 React Leaflet + Typescript 的 GeoJson 类型

问题描述 投票:0回答:1

我遇到了无法修复的类型错误:

<GeoJSON data={dataGeo} onEachFeature={featureClick} style={(feature: any) => getFeatureStyle(feature.properties.name)} />

错误:

Type '{ type: string; features: ({ type: string; properties: { featurecla: string; scalerank: number; labelrank: number; sovereignt: string; sov_a3: string; adm0_dif: number; level: number; type: string; ... 160 more ...; filename: string; }; geometry: { ...; }; } | ... 7 more ... | { ...; })[]; }' is not assignable to type 'GeoJsonObject'.
  Types of property 'type' are incompatible.
    Type 'string' is not assignable to type '"FeatureCollection" | "Feature" | "Polygon" | "MultiPolygon" | "Point" | "MultiPoint" | "LineString" | "MultiLineString" | "GeometryCollection"'.

我的 GeoJson 结构:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
       ...
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [...
          ]
        ]
      }
    }

提前致谢

reactjs typescript react-leaflet
1个回答
0
投票

您尝试使用无类型对象作为数据参数。尝试更改您的代码:

<GeoJSON data={dataGeo} onEachFeature={featureClick} style={(feature: any) => getFeatureStyle(feature.properties.name)} />

至:

<GeoJSON data={dataGeo as GeoJsonObject} onEachFeature={featureClick} style={(feature: any) => getFeatureStyle(feature.properties.name)} />

或者在组件头部定义 dataGeo 变量:

import { GeoJsonObject } from "geojson";
...
dataGeo: GeoJsonObject;
© www.soinside.com 2019 - 2024. All rights reserved.