2017-01-26 3 views
0

私はreact + google maps APIに問題があります。このGoogleマップイベントにthis.mapを渡すにはどうすればよいですか?

私は私のコンストラクタでthis.mapの値を設定しています:

constructor(props) { 
    super(props); 
    this.map = null; 
    } 

私はGoogle MapsのAPIをロードし、componentWillReceiveProps方法で私のマップを設定しています:

componentWillReceiveProps({ isScriptLoaded, isScriptLoadSucceed }) { 
    if (isScriptLoaded && !this.props.isScriptLoaded) { // load finished 
     console.log('yes - isScriptLoaded && !this.props.isScriptLoaded'); 
     if (isScriptLoadSucceed) { 
     this.map = new google.maps.Map(this.refs.map, mapOptions); 

     /* not sure how to do this part */ 
     google.maps.event.addDomListener(window, 'resize', function() { 
      const center = this.map.getCenter(); //this.map undefined, unless above I add const map = this.map, and then use map. 
      google.maps.event.trigger(this.map, 'resize'); 
      this.map.setCenter(center); 
     }); 

方法はあります私は別の変数const map = this.mapか何かを作成して渡す以外にthis.mapを渡すことができますか?

I午前心配私は矢印の機能を使用すると、内部のthisにアクセスできるようにすることを考えてthis.map値:(

答えて

0

を更新するのを忘れた場合const map = this.mapを使用して、ちょうどmapにさらに修正することで問題につながること匿名関数を変更する場合は、それを行うことができるかもしれない:。

これと
google.maps.event.addDomListener(window, 'resize', function() { 
     const center = this.map.getCenter(); //this.map undefined, unless above I add const map = this.map, and then use map. 
     google.maps.event.trigger(this.map, 'resize'); 
     this.map.setCenter(center); 
    }); 

google.maps.event.addDomListener(window, 'resize',() => { 
      const center = this.map.getCenter(); //this.map undefined, unless above I add const map = this.map, and then use map. 
      google.maps.event.trigger(this.map, 'resize'); 
      this.map.setCenter(center); 
     }); 

一般にReact.jsの属性としてコンテキストに値を直接割り当てることはお勧めできません。コンポーネントの状態は通常の方法です。しかし、GoogleマップのAPIを自分で使用していないのに、mapthisに直接割り当てる理由があると思います。

関連する問題