向react-leaflet标记组件添加新属性的TypeScript问题

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

我正在尝试将附加属性

count
传递到
Marker
提供的
react-leaflet
组件中。

但是,我们遇到了错误

Type '{ children: Element; position: [number, number]; key: number; count: number; }' is not assignable to type 'IntrinsicAttributes & MarkerProps & RefAttributes<Marker<any>>'.
  Property 'count' does not exist on type 'IntrinsicAttributes & MarkerProps & RefAttributes<Marker<any>>'.  TS2322

有办法解决这个问题吗?

Marker
现有的TS接口可以扩展吗?

反应/TS代码:

interface IMarker {
    lat: number;
    lon: number;
    count: number;
}

interface IProps {
    data: IMarker[];
}

const createClusterIcon = (cluster: any) => {
    const childMarkers = cluster.getAllChildMarkers();
    let childCount = 0;
    childMarkers.forEach((m:IMarker) => {
        childCount = childCount + m.options.count;
    });

    return L.divIcon({
        html: `<div><span>${childCount}</span></div>`,
        className: 'marker-cluster-small',
        iconSize: new L.Point(40, 40)
    })
}

export function MapView({data}: IProps): JSX.Element {
    // Combine markers in `data` array
    let markers = [];
    for (var i = 0; i < data.length; i++) {
        markers.push(...data[i]);
    }

    return (
        <MapContainer>
            <MarkerClusterGroup iconCreateFunction={createClusterIcon}>
                {
                    markers.map((marker, index) => (
                        <Marker 
                            position={[marker.lat, marker.lon]} 
                            key={index}
                            count={ marker.count }
                        />
                }
            </MarkerClusterGroup>  
        </MapContainer>  
    )
}
javascript reactjs typescript leaflet react-leaflet
1个回答
3
投票

您可以使用从 core 包导出的方法创建“own”标记组件。
检查Marker组件的实现。
换句话说,复制 Marker React 组件的实现并更改它。
例如这样:

export interface CustomMarkerProps extends MarkerOptions, EventedProps {
  children?: ReactNode;
  position: LatLngExpression;
  // custom object to be associated with a leaflet's marker
  customAttr: Object;
}

export const CustomMarker = createLayerComponent<LeafletMarker, CustomMarkerProps>(
  function createMarker({ customAttr, position, ...options }, ctx) {
    const instance = new LeafletMarker(position, options);
    // add customAttr to the leaflet's instance (leaflet, not the react wrapper)
    // @ts-ignore
    instance.customAttr = customAttr;
    return { instance, context: { ...ctx, overlayContainer: instance } };
  },
  function updateMarker(marker, props, prevProps) {
    // same as in the react-leaflet
  }
);

稍后您可以访问传单的实例并检索您的 customAttr。

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