【问题标题】:How to fix 'TS2769 No overload matches this call' when using react-leaflet使用 react-leaflet 时如何修复“TS2769 没有重载匹配此调用”
【发布时间】:2020-04-10 21:09:38
【问题描述】:

我正在尝试在我的 react 应用程序上实现 Leaflet 地图组件。这就是我的组件的样子:

import React from "react";
import { Map, Marker, Popup, TileLayer } from "react-leaflet";
import "./styles.scss";

const position = [51.505, -0.09];

const LocationMap: React.FC = () => {
  return (
    <section className="find-container container">
      <h2 className="find-title title">Find us</h2>
      <Map center={position} zoom={12}>
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution="&copy; <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
        />
      </Map>
    </section>
  );
};

export default LocationMap;

当我运行“npm start”时,项目编译失败,并显示此错误:

No overload matches this call.
  Overload 1 of 2, '(props: Readonly<MapProps>): Map<MapProps, Map>', gave the following error.
    Type 'number[]' is not assignable to type 'LatLng | LatLngLiteral | LatLngTuple | undefined'.
      Type 'number[]' is missing the following properties from type '[number, number]': 0, 1
  Overload 2 of 2, '(props: MapProps, context?: any): Map<MapProps, Map>', gave the following error.
    Type 'number[]' is not assignable to type 'LatLng | LatLngLiteral | LatLngTuple | undefined'.
      Type 'number[]' is not assignable to type 'LatLngTuple'.  TS2769

有人知道怎么解决吗?

【问题讨论】:

    标签: reactjs typescript react-leaflet


    【解决方案1】:

    TypeScript 抱怨,因为 center 属性被声明为数组 (number[]),而它应该是元组类型:

    const position:[number,number] = [51.505, -0.09];
    

    LatLngLiteral 输入:

    const position: LatLngLiteral = { lat: 51.505, lng: -0.09 };
    

    LatLng 输入:

    const position = new LatLng(51.505,-0.09);
    

    总而言之,要将react-leaflet 与 TypeScript 一起使用,需要安装以下软件包:

    • leaflet 作为依赖项
    • react-leaflet 和类型定义 @types/react-leaflet

    最后但同样重要的是,需要包含 as per documentation 传单 CSS 文件,例如,通过 index.html

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"
       integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
       crossorigin=""/>
    

    【讨论】:

      猜你喜欢
      • 2020-02-18
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      • 2021-03-13
      相关资源
      最近更新 更多