如何在ReactJS中使用window对象?

你好,摩托罗拉:

我想在自己内部加载Google API客户端库index.html并且onLoad='someMethod'会在单独的javascript文件中调用方法。然后,该方法将输出到控制台。

客户端库已加载,没有任何问题,但是消息没有从控制台中打印出来,我认为这是因为根本没有调用该方法。

这是我的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>

这是包含handleGoogleClientLoad方法的javascript文件

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

如果这是纯JavaScript,则该方法将如下所示:

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

es6中是否有任何与window对象相似的东西

磨损:

组件方法未附加到window对象。MyApp.handleGoogleClientLoad不会被别名化为window.handleGoogleClientLoadgoogle API脚本可能尝试调用的别名

如果您希望Google API在组件上调用方法,则会遇到一些麻烦,因为无法保证在加载Google API脚本之前或之后会挂载组件。如果要保证必须在组件安装后注入脚本,然后在componentDidMount方法中注册该函数您可以使用类似loadjs的东西

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章