day*_*mer 12 javascript reactjs google-signin
我正在尝试使用React 集成Google Sign In(链接).
我发现了一个问题,在过去使用google登录按钮和react 2解决了这个问题
我复制了与上述相同的步骤.在我的index.html手中
<script src="https://apis.google.com/js/platform.js?onload=triggerGoogleLoaded" async defer></script>
<script type="text/javascript">
function triggerGoogleLoaded() {
console.log("google event loaded");
window.dispatchEvent(new Event('google-loaded'));
}
</script>
Run Code Online (Sandbox Code Playgroud)
然后我Component看起来像
var LoginButton = React.createClass({
onSignIn: function(googleUser) {
console.log("user signed in"); // plus any other logic here
},
renderGoogleLoginButton: function() {
console.log('rendering google signin button');
gapi.signin2.render('my-signin2', {
'scope': 'https://www.googleapis.com/auth/plus.login',
'width': 200,
'height': 50,
'longtitle': true,
'theme': 'light',
'onsuccess': this.onSignIn
})
},
componentDidMount: function() {
window.addEventListener('google-loaded',this.renderGoogleLoginButton);
},
render: function() {
let displayText = "Sign in with Google";
return (
<div class="g-signin2" data-onsuccess="onSignIn"></div>
);
}
});
export default LoginButton;
Run Code Online (Sandbox Code Playgroud)
当我使用程序运行时yarn start,我得到了
/Users/Harit.Himanshu/bl/sources/webs/google-login/src/LoginButton.js
11:9 error 'gapi' is not defined no-undef
26:13 warning 'displayText' is assigned a value but never used no-unused-vars
? 2 problems (1 error, 1 warning)
Run Code Online (Sandbox Code Playgroud)
完整的源代码可从https://github.com/hhimanshu/google-login-with-react获得
有人可以帮我理解我的错误吗?
谢谢
Ste*_*per 13
在我看来,你正在加载谷歌apis作为脚本标签,我们期望将其设置window.gapi为谷歌API.但是,您正在运行eslint或其他一些检查程序,并且不知道该window.gapi应该存在.它失败了,因为它看到你使用未声明的变量.
一个便宜的解决方法是告诉Eslint你知道自己在做什么;
/* global gapi */
Run Code Online (Sandbox Code Playgroud)
将它放在文件的顶部,eslint将gapi视为已知的全局变量.
这对我有用。把它放在 componentDidMount 或构造函数中:
componentDidMount() {
window.gapi.load('auth2', () => {
// Retrieve the singleton for the GoogleAuth library and set up the client.
this.auth2 = window.gapi.auth2.init({
client_id: '436676563344-.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
});
this.auth2.attachClickHandler(this.refs.googleButton, {},
(googleUser) => {
this.googleLogin(googleUser.getBasicProfile());
}, (error) => {
});
});
}
Run Code Online (Sandbox Code Playgroud)
您还可以尝试包gapi-script,该包立即提供gapi,因此您不必等待任何脚本加载,只需导入它并使用:
import { gapi } from 'gapi-script';
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6695 次 |
| 最近记录: |