为什么onMapClicked可以工作,但onGpsClicked不能工作this.setState显示错误TypeError:无法读取未定义的onGpsClicked的属性'setState‘...................................................................................

import React from "react";
import { Map, Marker, GoogleApiWrapper } from "google-maps-react";
import GpsFixedRoundedIcon from "@material-ui/icons/GpsFixedRounded";
import Button from "@material-ui/core/Button";
export class SimpleMap extends React.Component {
constructor(props) {
super(props);
this.state = {
lat: this.props.lat,
lng: this.props.lng,
markers: [
{
position: { lat: this.props.lat, lng: this.props.lng },
},
],
};
this.onMapClicked = this.onMapClicked.bind(this);
this.onGpsClicked = this.onGpsClicked.bind(this);
}
onMapClicked(t, map, coord) {
if (this.props.activeStep === 1 || this.props.disable === false) {
const { latLng } = coord;
const lat = latLng.lat();
const lng = latLng.lng();
this.setState((previousState) => {
return {
markers: [
{
position: { lat, lng },
},
],
};
});
this.props.onChange(lat, lng);
}
}
onGpsClicked() {
navigator.geolocation.getCurrentPosition(function (position) {
this.setState({
lat: position.coords.latitude,
lng: position.coords.longitude,
});
});
}
发布于 2020-05-21 18:38:59
navigator.geolocation.getCurrentPosition(function (position) {
this.setState({
lat: position.coords.latitude,
lng: position.coords.longitude,
});
});React在这里不理解this,因为它引用的是函数作用域,而不是React作用域。您可以将语法更改为胖箭头函数,该函数使用词汇作用域/this
navigator.geolocation.getCurrentPosition( (position) => {
this.setState({
lat: position.coords.latitude,
lng: position.coords.longitude,
});
});https://stackoverflow.com/questions/61932550
复制相似问题