React, accessing a var from a script in a component

前端 未结 3 1533
旧时难觅i
旧时难觅i 2021-01-24 17:46

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

index.html file

3条回答
  •  情书的邮戳
    2021-01-24 18:08

    In general you can import a script with the following:

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

    NOTE: Before you can use the variable, the script has to load in!

    After the script is loaded you can use a variable from the script with

    window.variable
    

    (in this case)

    window.google.maps.whatever
    

    If you want to use a variable directly after a script is imported (on page load etc) you can do something like this:

    let aScript = document.createElement('script');
    aScript.type = 'text/javascript';
    aScript.src = "link to script";
    
    document.head.appendChild(aScript);
    
    aScript.onload = function() {
        window.variableFromScript.whatever
    }
    
    

提交回复
热议问题