React-Leaflet显示TS2769:没有重载与该调用匹配。 TypeError

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

我已经使用react-leaflet制作了一个映射组件,它确实运行良好,但是只有在下面的示例中添加@ts-ignore行时,才能构建它。如果我不这样做,我会收到一条错误消息:

TS2769: No overload matches this call.

如果输出postition的值,我会得到[13.298034302, 43.0488191271]imageBounds会给我[{lat: 14.194809302, lng: 42.3558566271}, {lat: 12.401259302, lng: 43.7417816271}](我也尝试过将它作为值的数组,而对象没有相同的结果。

我看不到哪里出了问题,如果可以帮助,我宁愿不发布带有@ ts-ignore的代码。

这里是代码:


import React from 'react'
import { Map, Marker, Popup, TileLayer } from 'react-leaflet'

/* Import Types */
import PropTypes from './types/props'

/* Import Stylesheet */
import './leaflet.css'
import styles from './styles.module.scss'

const defaultProps: PropTypes = {
  bounds: {
    imageTop: 0,
    imageLeft: 0,
    imageRight: 0,
    imageBottom: 0
  },
  tileLayer: {
    url: '',
    attribution: ''
  },
  minZoom: 8,
  maxZoom: 12,
  touchZoom: true,
  zoom: 10,
  zoomDelta: 0.25,
  zoomSnap: 0.25,
  zoomControl: true,
  attributionControl: false,
  zoomAnimation: false
}

/* Render component */
export const Mapping: React.FunctionComponent<PropTypes> = ({
  bounds,
  tileLayer,
  minZoom,
  maxZoom,
  touchZoom,
  zoom,
  zoomDelta,
  zoomSnap,
  zoomControl,
  attributionControl,
  zoomAnimation
}: PropTypes) => {
  const { imageTop, imageLeft, imageRight, imageBottom } = bounds
  const position = [(imageTop + imageBottom) / 2, (imageLeft + imageRight) / 2]
  const imageBounds = [{ lat: imageTop, lng: imageLeft }, { lat: imageBottom, lng: imageRight }]

  return (
    <Map
      // @ts-ignore
      bounds={imageBounds}
      className={styles['map-container']}
      zoom={zoom}
      zoomDelta={zoomDelta}
      zoomSnap={zoomSnap}
      minZoom={minZoom}
      zoomControl={zoomControl}
      maxZoom={maxZoom}
      touchZoom={touchZoom}
      zoomAnimation={zoomAnimation}
      attributionControl={attributionControl}
    >
      <TileLayer
        url={tileLayer.url}
        attribution={tileLayer.attribution}

      />

      <Marker
        // @ts-ignore
        position={position}>
        <Popup>A pretty CSS3 popup.<br />Easily customizable.</Popup>
      </Marker>
    </Map>
  )
}
Mapping.defaultProps = defaultProps

export default Mapping
reactjs typescript leaflet react-leaflet
1个回答
1
投票

由于您正在使用打字稿,因此您需要使用接口显式声明原型:

interface IMapping {
  bounds?: [number, number][] | LatLngBounds | undefined;
  tileLayer?: {
    url: string;
    attribution: string;
  };
  zoom?: number;
  minZoom?: number;
  maxZoom?: number;
  touchZoom?: boolean;
  zoomDelta?: number;
  zoomSnap?: number;
  zoomControl?: boolean;
  attributionControl?: boolean;
  zoomAnimation?: boolean;
}

包括Mapping组件时,所有这些都必须作为道具传递。在示例中,我使用?来使示例不需要道具。如果不包括?,它使道具成为可选,则会出现以下错误:

“以下属性中缺少类型'{}'...”

然后像这样使用它:

const Mapping: React.FC<IMapping> = ....

positionimageBounds变量等...相同:

const position: [number, number] = [13.298034302, 43.0488191271];

您需要声明变量的类型。

这里是demo,类型中包含了大多数代码,以帮助您开始对项目进行类型声明。

© www.soinside.com 2019 - 2024. All rights reserved.