简体   繁体   English

如何将this.map传递到此Google Map事件中?

[英]How can I pass this.map into this google map events?

I'm facing some trouble with react + google maps API. 我在使用React + Google Maps API时遇到了一些麻烦。

I am setting the value of this.map in my constructor: 我在构造函数中设置this.map的值:

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

I am loading the google maps API and setting up my map in the componentWillReceiveProps method: 我正在加载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);
        });

Is there a way I can pass this.map besides create another variable const map = this.map or something and passing that? 除了创建另一个变量const map = this.map东西,还有什么方法可以传递this.map

I am worried that by using const map = this.map and then modifying further on just map will lead to issues if I forget to update this.map value :( 我担心如果我忘记更新this.map值,使用const map = this.map然后再对map进一步修改会导致问题。

I think that using an arrow function to be able to access this inside an anonymous function. 我认为使用箭头函数能够在匿名函数内部访问this函数。 You might be able to do it if you change: 如果您进行以下更改,您也许可以做到:

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);
    });

with this: 有了这个:

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);
        });

In general I wouldn't recommend assigning values directly to the context as attributes in React.js and the component's state is the usual way to go. 通常,我不建议将值直接分配给上下文作为React.js中的属性,而组件的状态是通常的处理方式。 But even though I haven't used the Google Map's API myself I guess that there is a good reason to do assign map directly to this because I've seen a couple of places where it's done this way. 但是,即使我自己没有使用过Google Map的API,我还是认为有充分的理由直接将map分配给this因为我已经看到了很多这样做的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM