gpt4 book ai didi

javascript - Google 登录按钮不会在 React 中呈现

转载 作者:行者123 更新时间:2023-11-29 20:52:11 30 4
gpt4 key购买 nike

构建一个简单的 React 项目,并想添加一个登录页面。目前,谷歌登录按钮没有出现。 div 本身出现,但其中没有呈现任何按钮。

index.html

<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="CLIENT_ID.apps.googleusercontent.com">

src/components/Login.js

import React, { Component } from 'react';
class Login extends Component {
onSignIn(googleUser) {
console.log("Signing In!")
var profile = googleUser.getBasicProfile();
document.getElementById('status').innerHTML = 'Thanks for logging in using Google, ' + profile.getName() + '!';
}

render() {
return (
<div className="socialwrapper" style={{textAlign: "center", paddingTop: 200}}>
<script src="https://apis.google.com/js/api:client.js"></script>
<div className="g-signin2" data-onsuccess="onSignIn"></div>
<div id="status">"Here is the status"</div>
</div>
);
}
}


export default Login;

不知道哪里出了问题。是 index.html 没有加载?我试过重新启动服务器,并仔细检查了 CLIENT_ID 是否正确。 onSignIn 中的 console.log 不触发。除此之外,我不确定该怎么做。

最佳答案

这个问题是在深入研究将外部脚本包含到 React 组件中后解决的,这是由 Jun Bin 的评论引发的探索。最终我找到了this bit of code来自 this tutorial解决了这个问题。虽然按钮仍然不能完全工作,但它至少会出现。修改后的代码如下,如果按钮完全可用,我将对其进行编辑。

// src/components/Login.js
import React, { Component } from 'react';
class Login extends Component {
componentDidMount() {
(function() {
var e = document.createElement("script");
e.type = "text/javascript";
e.async = true;
e.src = "https://apis.google.com/js/client:platform.js?onload=gPOnLoad";
var t = document.getElementsByTagName("script")[0];
t.parentNode.insertBefore(e, t)
})();
}
onSignIn(googleUser) {
console.log("Signing In!")
var profile = googleUser.getBasicProfile();
document.getElementById('status').innerHTML = 'Thanks for logging in using Google, ' + profile.getName() + '!';
}

render() {
return (
<div className="socialwrapper" style={{textAlign: "center", paddingTop: 200}}>
<div className="g-signin2" data-onsuccess="onSignIn"></div>
<div id="status">Here is the status</div>
</div>
);
}
}

关于javascript - Google 登录按钮不会在 React 中呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51356112/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com