繁体   English   中英

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

[英]TypeScript Problem with Adding New Property to react-leaflet Marker Component

我正在尝试将额外的属性count传递给react-leaflet提供的Marker组件。

但是,我们收到一个错误

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>  
    )
}

您可以使用从核心package 导出的方法创建“自己的”标记组件。
检查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)
    instance.customAttr = customAttr;
    return { instance, context: { ...ctx, overlayContainer: instance } };
  },
  function updateMarker(marker, props, prevProps) {
    // same as in the react-leaflet
  }
);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM