React,从组件中的脚本访问var [英] React, accessing a var from a script in a component

查看:157
本文介绍了React,从组件中的脚本访问var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



index.html file

 < div id =app>< / div> 
< script type =text / javascriptsrc =https://maps.googleapis.com/maps/api/js?key=MY_API_KEY_GOES_HERE&callback=initMapasync defer>

反应档案

  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>我是地图组件< / p>
< div id =mapref =map/>
< / div>
}

我得到的错误是:


未捕获ReferenceError:google未定义


正在工作。如何从组件中的此脚本访问变量?



这只是一个示例,请不要告诉我为React Google地图使用其中一个NPM软件包。



谢谢,
Harris

解决方案

是因为在加载React组件之前,并没有加载google api。



在加载您的反应脚本之前,将标记的标签放在标题中。

 < head> 
< script type =text / javascriptsrc =https://maps.googleapis.com/maps/api/js?key=MY_API_KEY_GOES_HERE&callback=initMapasync defer>

<! - 此处反应脚本 - >
< / head>

如果仍有问题,请尝试添加调试器; code>在> didComponentMount()函数行中,并在控制台中检查 google 是否已加载并可用。 / p>

I have been trying to import an external library (google Maps) in order to use it in a React component

index.html file

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

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

The error I get is:

Uncaught ReferenceError: google is not defined

I have tried everything but nothing seems to be working. How do I access the variable from this script inside my component?

This is just an example, please do not tell me to use one of the NPM packages for React Google Maps.

Thanks, Harris

解决方案

The error is because the google api is not loaded before your React Component is loading.

Place the script tag for google in the header, before loading your react scripts.

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

If you're still having trouble, try adding a debugger; line in didComponentMount() function and check in the console if google is loaded and available.

这篇关于React,从组件中的脚本访问var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆