我正在尝试在我的react应用程序上实现Leaflet map组件。这是我的组件的样子:
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="© <a href="http://osm.org/copyright">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
有人知道如何解决吗?
答案 0 :(得分:0)
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);
总而言之,要在TypeScript中使用react-leaflet
,需要安装以下软件包:
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=""/>