React,从组件中的脚本访问 var

Eri*_*kos 1 javascript google-maps reactjs

我一直在尝试导入一个外部库(谷歌地图)以便在 React 组件中使用它

index.html文件

<div id="app"></div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY_GOES_HERE&callback=initMap" async defer>
Run Code Online (Sandbox Code Playgroud)

反应文件

  componentDidMount() {
    this.map = new google.maps.Map(this.refs.map, {
      center: {lat: this.props.lat, lng: this.props.lng},
      zoom: 8
    });   
  }

    render() {
      return <div>
        <p>I am a map component</p>
        <div id="map" ref="map"/>
      </div>
    }
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

未捕获的 ReferenceError:未定义 google

我已经尝试了一切,但似乎没有任何效果。如何从我的组件内的这个脚本访问变量?

这只是一个例子,请不要告诉我使用 React Google Maps 的 NPM 包之一。

谢谢,哈里斯

Dar*_*isa 8

聚会有点晚了,但我也遇到了这个问题,对我来说这是由 eslint 引起的。要禁用它,只需/*global google*/在声明变量的地方添加上面的注释 ,它应该可以工作,例如

  componentDidMount() {
    /*global google*/ // To disable any eslint 'google not defined' errors
    this.map = new google.maps.Map(this.refs.map, {
      center: {lat: this.props.lat, lng: this.props.lng},
      zoom: 8
    });   
  }

    render() {
      return <div>
        <p>I am a map component</p>
        <div id="map" ref="map"/>
      </div>
    }
Run Code Online (Sandbox Code Playgroud)

您还可以使用 window 对象进行调用:

  componentDidMount() {
    /* Use new window.google... instead of new google... */
    this.map = new window.google.maps.Map(this.refs.map, {
      center: {lat: this.props.lat, lng: this.props.lng},
      zoom: 8
    });   
  }

    render() {
      return <div>
        <p>I am a map component</p>
        <div id="map" ref="map"/>
      </div>
    }
Run Code Online (Sandbox Code Playgroud)