如何解决向 react-leaflet 标记组件添加新属性的 TypeScript 问题
我正在尝试将附加属性 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接口?
React/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>
)
}
解决方法
您可以使用从 core 包导出的方法创建“自己的”标记组件。
检查 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。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。