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

IT技术 javascript google-maps reactjs
2021-05-12 00:37:01

我一直在尝试导入一个外部库(谷歌地图)以便在 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>

react文件

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

我得到的错误是:

未捕获的 ReferenceError:未定义 google

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

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

谢谢,哈里斯

3个回答

聚会有点晚了,但我也遇到了这个问题,对我来说这是由 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>
    }

您还可以使用 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>
    }

错误是因为在加载 React 组件之前未加载 google api。

在加载您的react脚本之前,将 google 的脚本标记放在标题中。

<head>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY_GOES_HERE&callback=initMap" async defer>

    <!-- React scripts here -->
</head>

如果您仍然遇到问题,请尝试debugger;didComponentMount()函数中添加一行并检查控制台是否google已加载且可用。

通常,您可以使用以下内容导入脚本:

let aScript = document.createElement('script');
aScript.type = 'text/javascript';
aScript.src = "link to script";
document.head.appendChild(aScript);

注意:在使用变量之前,必须加载脚本!

加载脚本后,您可以使用脚本中的变量

window.variable

(在这种情况下)

window.google.maps.whatever

如果您想在导入脚本后(在页面加载等时)直接使用变量,您可以执行以下操作:

let aScript = document.createElement('script');
aScript.type = 'text/javascript';
aScript.src = "link to script";

document.head.appendChild(aScript);

aScript.onload = function() {
    window.variableFromScript.whatever
}