google redux 形式的地图

google maps in redux form

我想使用 google 地图通过 redux 形式获取纬度和经度。我创建这个:

import React from 'react';
import { compose, withProps, lifecycle } from 'recompose';
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from 'react-google-maps';

const MyMapComponent = compose(
    withProps({
        googleMapURL:
            'https://maps.googleapis.com/maps/api/js?key=AIzaSyCYSleVFeEf3RR8NlBy2_PzHECzPFFdEP0&libraries=geometry,drawing,places',
        loadingElement: <div style={{ height: `100%` }} />,
        containerElement: <div style={{ height: `400px` }} />,
        mapElement: <div style={{ height: `100%` }} />,
    }),
    lifecycle({
        componentWillMount() {
            const refs = {};

            this.setState({
                position: null,
                onMarkerMounted: ref => {
                    refs.marker = ref;
                },

                onPositionChanged: () => {
                    const position = refs.marker.getPosition();
                    console.log(position.toString());
                },
            });
        },
    }),
    withScriptjs,
    withGoogleMap
)(props => (
    <GoogleMap defaultZoom={8} defaultCenter={{ lat: -34.397, lng: 150.644 }}>
        {props.isMarkerShown && (
            <Marker
                position={{ lat: -34.397, lng: 150.644 }}
                draggable={true}
                ref={props.onMarkerMounted}
                onPositionChanged={props.onPositionChanged}
            />
        )}
    </GoogleMap>
));

class MyParentComponentWrapper extends React.PureComponent {
    state = {
        isMarkerShown: false,
    };

    render() {
        return (
            <div>
                <MyMapComponent isMarkerShown={true} />
            </div>
        );
    }
}

export default MyParentComponentWrapper;

但它 return 没有任何值,并且在该字段中不显示纬度和经度 我该怎么办?当用户拖动标记

时,它将 console.log 纬度和经度

如果你想 MyMapComponent 到 return 到 MyParentComponentWrapper 的值,只需传递一个回调函数作为 prop。只需将父组件更改为:

<MyMapComponent isMarkerShown={true} onMakerPositionChanged={this.onMakerPositionChanged}/>

地图组件为:

onPositionChanged: () => { const position = refs.marker.getPosition(); console.log(position.toString()); this.props.onMakerPositionChanged(position); },

查看工作示例 here