react-google-maps 在执行 onclick 时刷新地图
react-google-maps is refreshing the map when onclick is performed
我正在尝试在我的应用程序中使用 react-google-maps 作为纬度和经度输入。为了获得用户选择的位置,我使用了 onclick 事件,它几乎按预期工作,因为标记已设置,但地图正在刷新并转到默认中心并在用户选择所需位置时缩放。我怎样才能避免这种奇怪的行为?
import React from "react";
import { withScriptjs, withGoogleMap, GoogleMap, Marker, MarkerWithLabel } from "react-google-maps";
export default class MapTest extends React.Component {
constructor(){
super();
this.state={
isMarkerShown: false,
markerPosition: null
}
}
onMapClick= (e) => this.setState({
markerPosition: e.latLng,
isMarkerShown:true}
);
render() {
var Map= withScriptjs(withGoogleMap((props) =>
<GoogleMap
defaultZoom={12}
center={ { lat: 4.4360051, lng: -75.2076636 } }
onClick={this.onMapClick}
>
{this.state.isMarkerShown && <Marker position={this.state.markerPosition} />}
</GoogleMap>));
return (<Map {...this.props} />);
}
}
那是因为您在每次 render
调用中都创建了一个新对象。
withScriptjs(withGoogleMap
应该存放在某个地方以供重复使用
例如
class MapTest extends React.Component {
//...
Map = withScriptjs(
withGoogleMap(props => (
<GoogleMap
defaultZoom={12}
center={{ lat: 4.4360051, lng: -75.2076636 }}
onClick={props.onClick}
>
{props.children}
</GoogleMap>
))
);
render() {
return <this.Map {...this.props} onClick={this.onMapClick}>
{this.state.isMarkerShown && (
<Marker position={this.state.markerPosition} />
)}
</this.Map>;
}
}
我正在尝试在我的应用程序中使用 react-google-maps 作为纬度和经度输入。为了获得用户选择的位置,我使用了 onclick 事件,它几乎按预期工作,因为标记已设置,但地图正在刷新并转到默认中心并在用户选择所需位置时缩放。我怎样才能避免这种奇怪的行为?
import React from "react";
import { withScriptjs, withGoogleMap, GoogleMap, Marker, MarkerWithLabel } from "react-google-maps";
export default class MapTest extends React.Component {
constructor(){
super();
this.state={
isMarkerShown: false,
markerPosition: null
}
}
onMapClick= (e) => this.setState({
markerPosition: e.latLng,
isMarkerShown:true}
);
render() {
var Map= withScriptjs(withGoogleMap((props) =>
<GoogleMap
defaultZoom={12}
center={ { lat: 4.4360051, lng: -75.2076636 } }
onClick={this.onMapClick}
>
{this.state.isMarkerShown && <Marker position={this.state.markerPosition} />}
</GoogleMap>));
return (<Map {...this.props} />);
}
}
那是因为您在每次 render
调用中都创建了一个新对象。
withScriptjs(withGoogleMap
应该存放在某个地方以供重复使用
例如
class MapTest extends React.Component {
//...
Map = withScriptjs(
withGoogleMap(props => (
<GoogleMap
defaultZoom={12}
center={{ lat: 4.4360051, lng: -75.2076636 }}
onClick={props.onClick}
>
{props.children}
</GoogleMap>
))
);
render() {
return <this.Map {...this.props} onClick={this.onMapClick}>
{this.state.isMarkerShown && (
<Marker position={this.state.markerPosition} />
)}
</this.Map>;
}
}