Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

javascript - How do I use the window object in ReactJS?

I want to load the Google APIs client library inside my index.html and the onLoad='someMethod' will invoke a method in a separate javascript file. That method will then print out to the console.

The client library is loaded without any problems but the message is not getting printed out the console and I think it's because the method is not getting invoked at all.

Here is my index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Welcome</title>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>

<body>
    <div id="app"></div>
    <script src="lib/vendors.js"></script>
    <script src="build/bundle.js"></script>
    <script src="https://apis.google.com/js/client.js?onload=handleGoogleClientLoad"></script>
</body>

Here is the javascript file that contains the handleGoogleClientLoad method:

import React from 'react';
import ReactDOM from 'react-dom';

import {Button} from 'react-bootstrap';

class MyApp extends React.Component {

handleGoogleClientLoad() {
    console.log('Success on load');
}

render() {
    return (
        <div>
            <Button>Click Me</Button>
        </div>
    );
  }
}


const app = document.getElementById('app');

ReactDOM.render(<MyApp />, app);

If this was plain javascript the method would look like this:

window.handleGoogleClientLoad = function() {
  // Log to the console
};

Is there anything in es6 that is similar to the window object.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Component methods are not attached to the window object. MyApp.handleGoogleClientLoad is not going to be aliased to window.handleGoogleClientLoad which is what the google API script is likely trying to invoke.

If you want the Google API to call a method on your component you're going to have some trouble as there's no guarantee that your component will be mounted before or after your Google API script loads. If you want to guarantee that you'd have to inject the script after the component mounted and register the function in the componentDidMount method. You can use something like loadjs

componentDidMount() {
 window.handleGoogleClientLoad = function() {
  // log to console
 }
 loadjs('https://apis.google.com/js/client.js?onload=handleGoogleClientLoad')
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...