2

我正在尝试使用 react-yandex-maps 通过坐标获取地址。我知道如何在功能组件中做到这一点。但我真的需要改用类组件。我需要获取 ymaps。但不知道该怎么做。找不到解释清楚的文档。

这是我的代码:

import React, { Component } from 'react'
import { YMaps, Map, ZoomControl, FullscreenControl, SearchControl, GeolocationControl, Placemark } from "react-yandex-maps";

export default class YMap extends Component {
    constructor(props) {
        super(props)
        this.state = {
            coords: [],
            mapState: {
                center: [41.2825125, 69.1392826],
                zoom: 9
            },
        }
    }

    componentDidUpdate(prevProps, prevState) {
        if (prevProps.oldCoords !== this.props.oldCoords) {
            this.setState({ coords: this.props.oldCoords })
        }
    }

    onMapClick = (e) => {
        const coords = e.get("coords");
        this.setState({ coords: coords })
    };

    render() {
        return (
            <div>
                <YMaps query={{ apikey: "" }}>
                    <Map
                        modules={["Placemark", "geocode", "geoObject.addon.balloon"]}
                        onClick={this.onMapClick}
                        state={this.state.mapState}
                        width='100%'
                        height='500px'
                    >
                        {this.state.coords ? <Placemark geometry={this.state.coords} /> : null}
                        <ZoomControl />
                        <FullscreenControl />
                        <SearchControl />
                        <GeolocationControl />
                    </Map>
                </YMaps>
            </div>
        )
    }
}
4

0 回答 0