在渲染器之外访问变量

时间:2019-12-24 19:38:50

标签: reactjs

我的代码有问题。我已经可以使用lat和lng在地图上做一个标记。但是 我想显示一个简单的跨度,并在地图下显示坐标 。我尝试访问this.props.markerPosition,并且在渲染中为空。

这是什么问题?

https://stackblitz.com/edit/react-snxake

const WrappedMap = compose(
    withStateHandlers(() => ({
        isMarkerShown: false,
        markerPosition: null
      }), {
        onMapClick: ({ isMarkerShown }) => (e) => ({
            markerPosition: e.latLng,
            isMarkerShown:true
        })        
      }),
    withScriptjs,
    withGoogleMap
    )
    (props =>
        <GoogleMap
            defaultZoom={8}
            defaultCenter={{ lat: -34.397, lng: 150.644 }}
            onClick={props.onMapClick}
        >
            {props.isMarkerShown && <Marker position={props.markerPosition} onClick={props.onMarkerClick} defaultOptions={{ styles: mapStyles}} />}
        </GoogleMap>
    )

export default class ParkingSpotsSettings extends React.Component {

    state = {
        evaluationExecuted: false,
        evaluation: false
    };

    constructor() {
        super();
        this.state = {
            coordinates: [],
            title: '',
            description: '',
            capacity: 0
        }
      }

    componentDidMount() { }


    render() {
   
        return (
            <div className="App">
                <Navigation />
                <div className="container-fluid">
                    <div className="row">
                        <div className="col-md-6" style={{ width: "100vw", height: "40vh" }}>
                            <WrappedMap googleMapURL={`https://maps.googleapis.com/maps/api/js?key=v=3.exp&libraries=geometry,drawing,places`}
                            loadingElement={<div style={{ height: "100%" }} />}
                            containerElement={<div style={{ height: "100%" }} />}
                            mapElement={<div style={{ height: "100%" }} />}
                            />
                            </div>

                            <span>Coordinates are: {this.props.markerPosition}</span>
                    </div>
                </div>
            </div >
        );
    }
}

1 个答案:

答案 0 :(得分:0)

您的道具叫position而不是markerPosition。因此,您需要使用this.props.position