【发布时间】:2018-03-19 23:14:47
【问题描述】:
我正在尝试在 componentDidMount 中设置位置。我猜this 没有被传递给内部函数。
看我的例子:
import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';
const map = {
width: '100%',
height: '100vh'
};
const AnyReactComponent = ({ text }) => <div>{ text }</div>;
export default class Map extends Component {
constructor(props) {
super(props)
this.state = {
center: { lat: 40.7446790, lng: -73.9485420 },
zoom: 11
}
};
componentDidMount(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(position) {
console.log(position);
this.setState({
center: { lat: position.coords.latitude, lng: position.coords.longitude },
})
}
)
}
}
render() {
return (
<div className='map' style={ map }>
<GoogleMapReact
bootstrapURLKeys={{ key: 'AIzaSyD3Gu9y1qJChfayVFglovKEY2xjgKBiCJA' }}
defaultCenter={ this.state.center }
defaultZoom={ this.state.zoom }>
<AnyReactComponent
lat={ 40.7473310 }
lng={ -73.8517440 }
text={ "Where's Waldo?" }
/>
</GoogleMapReact>
</div>
)
};
};
这种情况一直在发生,我不知道为什么。
你能帮忙吗?
【问题讨论】:
-
它甚至进入了if语句吗?
标签: reactjs geolocation