简体   繁体   English

为 react-component 提供传单地图

[英]provide leaflet-map to react-component

I'm using react-leaflet to render a map.我正在使用 react-leaflet 来渲染 map。 I created a component that has a map-property:我创建了一个具有地图属性的组件:

import * as React from 'react';
import { Map, FeatureCollection } from  'leaflet';

class Car extends React.Component {
    
    state = { 
        map: Map,
        collection: FeatureCollection
    }
    constructor(props) {
        super(props);
        this.state = { 
            map: props.map,
            collection: props.collection
        }
    }

Now I try to use that component within my app:现在我尝试在我的应用程序中使用该组件:

import React, { useState } from 'react';
import { MapContainer, useMap } from 'react-leaflet';
import Car from './Car';

function Layout() {

    return (
        <div>
            <MapContainer bounds={[[52.475,13.3], [52.477,13.5]]} zoom={12}>
                <Car map={ useMap() }/>
            </MapContainer> 
        </div>
    )
}

export default Layout;

However I don't know how to provide the map from the MapContainer into my Car -component.但是我不知道如何将 MapContainer 中的MapContainer提供到我的Car组件中。 Using the above code I get the following error:使用上面的代码我得到以下错误:

TS2322: Type '{ map: string; TS2322:类型'{ map:字符串; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; }' 不可分配给类型 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; }>'. }>'。 Property 'map' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode;类型“IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; }>'. }>'。

useMap can only be used within a component that is itself a child/descendant of <MapContainer> . useMap只能在本身是<MapContainer>的子/后代的组件中使用。 https://react-leaflet.js.org/docs/api-map/#usemap https://react-leaflet.js.org/docs/api-map/#usemap

Hook providing the Leaflet Map instance in any descendant of a MapContainer .在 MapContainer 的任何后代中提供 Leaflet Map 实例的MapContainer

Your <Layout> component renders such <MapContainer> , but is not within one.您的<Layout>组件呈现这样的<MapContainer> ,但不在一个

However, you can simply use useMap in the body of <Car>但是,您可以简单地在<Car>的主体中使用useMap

That being said, it will probably not work if you keep your <Car> component class-based.话虽如此,如果您保持<Car>组件基于类,它可能不会起作用。 You will probably have to either convert it to functional component, or use an older version of React Leaflet (2).您可能必须将其转换为功能组件,或使用旧版本的 React Leaflet (2)。

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

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