hel*_*oto 18 javascript ecmascript-6 reactjs
我想在我的内部加载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>
Run Code Online (Sandbox Code Playgroud)
这是包含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);
Run Code Online (Sandbox Code Playgroud)
如果这是普通的JavaScript,方法将如下所示:
window.handleGoogleClientLoad = function() {
// Log to the console
};
Run Code Online (Sandbox Code Playgroud)
es6中是否有与该window对象类似的内容.
Awe*_*ary 14
组件方法未附加到window对象.谷歌API脚本可能试图调用的东西MyApp.handleGoogleClientLoad不会被混淆window.handleGoogleClientLoad.
如果您希望Google API在您的组件上调用方法,那么您将遇到一些问题,因为无法保证在加载Google API脚本之前或之后安装您的组件.如果要保证在安装组件后必须注入脚本并在componentDidMount方法中注册该函数.你可以使用像loadjs这样的东西
componentDidMount() {
window.handleGoogleClientLoad = function() {
// log to console
}
loadjs('https://apis.google.com/js/client.js?onload=handleGoogleClientLoad')
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43238 次 |
| 最近记录: |