简体   繁体   中英

Access variables defined in <head> or external script from React component

I am integrating a third-party library into my React app. They provide this script I need to add to my <head> :

index.html

<head>
    <script>
      var externalVariable1 = externalVariable1 || {};
      var externalVariable2 = externalVariable2 || {};
    </script>
    // tag.min.js gives value to these variables
    <script async src="//example.com/tag.min.js"></script>
</head>

I need to use access these two variables from my component. I tried the following but I get 'externalVariable1' is not defined error. Any thoughts?

MyScreen.js

import React from 'react';

const MyScreen = () => {
    
    return (
        <React.Fragment>
            <div>
                <h2>Hello!</h2>
            </div>
    
            <div id='myId'>
                {externalVariable.push(function() { externalVariable2.display();})}
            </div>
        </React.Fragment>
    );

}

export default MyScreen;

If you want to access variables defined in the global scope from inside of a React component, you can typically do that by accessing the variable through the window object.

See the example below:

 function App(){ return <h1>The secret is {window.secret}</h1> } ReactDOM.render(<App />, document.getElementById("root"))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <;-- Adding some global variables outside of React --> <script> var secret = "hello"; </script> <div id="root"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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