我正在使用react google地图来微调地理位置函数之后的用户位置,这是我的Map.js代码的一部分:
const MyMapComponent = compose(
withProps({
googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIzaSyAKCqAqiyop85LNl9qUb6OAT1lJupLEnzo&v=3.exp&libraries=geometry,drawing,places",
loadingElement: <div style={{height: `100%`}}/>,
containerElement: <div style={{height: `400px`}}/>,
mapElement: <div style={{height: `100%`}}/>,
}),
withState(),
withHandlers(() => {
const refs = {
map: undefined,
}
return {
onMapMounted: () => ref => {
refs.map = ref
},
onBoundsChanged: ({onBoundsChanged}) => () => {
onBoundsChanged(refs.map.getCenter().lat(), refs.map.getCenter().lng())
}
}
}),
withScriptjs,
withGoogleMap
)((props) =>
<GoogleMap
defaultZoom={8}
defaultCenter={{lat: props.lat, lng: props.lng}}
ref={props.onMapMounted}
onBoundsChanged={props.onBoundsChanged}
>
<Marker position={{lat: props.lat, lng: props.lng}}/>
</GoogleMap>
)我只是想能够通过ref调用其他组件中的panTo()方法,在内部我没有问题,因为我认为ref在mapMounted方法( refs.map.getCenter( ) .lat() )中传递得很好,但是如何在外部调用这些方法,我的问题是我使用的是重组库。提前进行thx检查。
Home.js中的一部分代码,其中我使用了map并拥有我想要触发panTo()的get position方法:
import MyMapComponent from './Maps';
export default class HomeComponent extends React.Component {
render() {
const {showAlert, address, lat, lng} = this.props;
return (
<MyMapComponent
lat={lat}
lng={lng}
onBoundsChanged={this.props.handleOnBoundsChanged}
/>
<Button onClick={()=>this.props.getPosition()}>Usar mi
ubicación actual</Button>
)
}
}发布于 2018-08-30 07:15:02
您可以使用任何贴图方法创建道具。
...
withHandlers(() => {
let map;
return {
onMapMounted: () => ref => {
map = ref;
},
onBoundsChanged: ({ onBoundsChanged }) => () => {
onBoundsChanged(map.getCenter().lat(), map.getCenter().lng());
}
mapPanTo: () => args => map.panTo(args),
};
})
...现在,props.mapPanTo可以传递给任何其他组件。
https://stackoverflow.com/questions/52085023
复制相似问题