我正试图在我的react应用程序上实现一个传单映射组件。我的组件是这样的:
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
有人知道怎么修吗?
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
最后但同样重要的是,根据文档传单,CSS文件需要包括在内,例如,通过index.html
:
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"
integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
crossorigin=""/>