react-google-maps: 如何在父组件中使用 fitBounds API
react-google-maps: how to use fitBounds API in the parent component
我在此现场演示中重现了我的问题:
https://codesandbox.io/s/p3yv83o7x7
简单的说,在下面的代码中:
class MapWrapper extends React.Component {
constructor() {
super();
this.state = {
zoom: 8,
strictMode: false
};
this.mapRef = null;
this.onMapMounted = this.onMapMounted.bind(this);
this.setZoom = this.setZoom.bind(this);
this.setStrictMode = this.setStrictMode.bind(this);
this.handleClick = this.handleClick.bind(this);
}
setZoom() {
this.setState({ zoom: this.mapRef.getZoom() });
}
onMapMounted(ref) {
this.mapRef = ref;
}
setStrictMode(e) {
this.setState({ strictMode: e.target.checked });
}
handleClick() {
// Here I want the map fit a new bound
// With mapRef reference I can call fitBounds, it ok
// But how I can create a new bounds object with new google.map.LatLngBounds()?
// how I can access google lib here?
//this.mapRef.fitBounds()
}
render() {
return (
<div>
<button onClick={this.handleClick}>abc</button>
<MyMapComponent
isMarkerShown={this.state.zoom < 10}
onZoomChanged={this.setZoom}
onMapMounted={this.onMapMounted}
zoom={this.state.zoom}
/>
</div>
);
}
}
我的困惑点在handleClick
函数中标记为注释。在这个回调函数中,我想使用google映射mapRef
引用来调用fitBounds
API。但是为了 运行 这个 API,我需要用 new google.map.LatLngBounds()
创建一个新的 LatLngBounds
对象。但是如何访问父组件中的 google 库?这是我的困惑点
尝试使用 new window.google.map.LatLngBounds()
创建一个新的 LatLngBounds
对象
我在此现场演示中重现了我的问题: https://codesandbox.io/s/p3yv83o7x7
简单的说,在下面的代码中:
class MapWrapper extends React.Component {
constructor() {
super();
this.state = {
zoom: 8,
strictMode: false
};
this.mapRef = null;
this.onMapMounted = this.onMapMounted.bind(this);
this.setZoom = this.setZoom.bind(this);
this.setStrictMode = this.setStrictMode.bind(this);
this.handleClick = this.handleClick.bind(this);
}
setZoom() {
this.setState({ zoom: this.mapRef.getZoom() });
}
onMapMounted(ref) {
this.mapRef = ref;
}
setStrictMode(e) {
this.setState({ strictMode: e.target.checked });
}
handleClick() {
// Here I want the map fit a new bound
// With mapRef reference I can call fitBounds, it ok
// But how I can create a new bounds object with new google.map.LatLngBounds()?
// how I can access google lib here?
//this.mapRef.fitBounds()
}
render() {
return (
<div>
<button onClick={this.handleClick}>abc</button>
<MyMapComponent
isMarkerShown={this.state.zoom < 10}
onZoomChanged={this.setZoom}
onMapMounted={this.onMapMounted}
zoom={this.state.zoom}
/>
</div>
);
}
}
我的困惑点在handleClick
函数中标记为注释。在这个回调函数中,我想使用google映射mapRef
引用来调用fitBounds
API。但是为了 运行 这个 API,我需要用 new google.map.LatLngBounds()
创建一个新的 LatLngBounds
对象。但是如何访问父组件中的 google 库?这是我的困惑点
尝试使用 new window.google.map.LatLngBounds()
LatLngBounds
对象