2017-04-20 59 views
0

我想:如何调用函数getCenter()和其他反应 - 谷歌 - 地图

<GoogleMap 
    defaultZoom={14} 
    center={{lat: props.mapCenter.lat, lng: props.mapCenter.lng}} 
    onCenterChanged={getCenter()} 
/> 

更新:我使用的是Stateless Functional Component

const MarkerClustererExampleGoogleMap = withGoogleMap(props => (

    <GoogleMap 
     defaultZoom={14} 
     center={{lat: props.mapCenter.lat, lng: props.mapCenter.lng}} 
     onCenterChanged={getCenter()} 
    > 
) 

但我得到的错误:

getCenter is undefined.

如何解决此问题,谢谢。

回答

0

您需要使用这样的:

onCenterChanged={this.getCenter} 

注意onCenterChanged是一个事件,所以请确保您定义的构造函数的结合,这样

this.getCenter = this.getCenter.bind(this); 

,或者你也可以用arrow function,通过Arrow Function:

onCenterChanged={ (e)=> this.getCenter(e)} 

更新:你没有提到你正在使用Stateless Functional Component,无论何时询问问题,都尽量提供完整的信息。

检查这一点,如何界定functionStateless Functional Component

var App =() => { 
 

 
    var click = function() { 
 
     console.log('a'); 
 
    } 
 
    
 
    return(
 
     <div onClick={click}> Click </div> 
 
    ) 
 
} 
 

 
ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 

 
<div id='app'/>

+0

哦,我可以用喜欢你的决心,但我有无国籍的组成部分。而我的变量“this”没有定义。我用部件使用GoogleMap不变量 “这个” '常量MarkerClustererExampleGoogleMap = withGoogleMap(道具=>(

+0

@ cm-brain检查更新后的答案,如何在无状态功能组件中定义函数,写入方式与其工作方式相同。 –

0

看一看这个例子:Adding a places search box。 的这部分代码会告诉你正确的路径)

handleMapMounted(map) { 
    this._map = map; 
} 

handleBoundsChanged() { 
    this.setState({ 
    bounds: this._map.getBounds(), 
    center: this._map.getCenter(), 
}); 
}