首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在react中使用google登录按钮

在react中使用google登录按钮
EN

Stack Overflow用户
提问于 2015-07-24 20:22:31
回答 5查看 36.1K关注 0票数 43

我正在尝试在react应用程序中使用google登录。虽然在应用程序外部使用登录按钮效果很好,但在自定义SignIn组件中使用它时,我无法让它按预期工作。当用户登录时,按钮本身应该执行一个data-onsuccess方法。问题是,即使登录可以工作,执行也永远不会到达该方法。

我可能遗漏了一些反应陷阱,但我真的找不到它。有什么帮助吗?可以在下面找到加载所有内容和组件本身的html。

代码语言:javascript
复制
<head>
    <meta name="google-signin-scope" content="profile email">
    <meta name="google-signin-client_id" content="1234-real-client-id.apps.googleusercontent.com">
    <script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body>
    <!-- Here is where everything gets displayed -->
    <div id="app"></div>

    <!-- The file with the js code -->
    <script src="/js/main.js"></script>
</body>


var SignIn = React.createClass({
    onSignIn : function (google_user) {
        // I want this method to be executed
    },

    render : function() {
        return (
            <div className="g-signin2" data-onsuccess={this.onSignIn} data-theme="dark" />
        );
    }
});

请注意,我没有在这里粘贴不相关的代码;)

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2015-07-24 22:08:11

尝试在componentDidMount()中初始化组件时添加onSuccess回调。

代码语言:javascript
复制
componentDidMount: function() {
  gapi.signin2.render('g-signin2', {
    'scope': 'https://www.googleapis.com/auth/plus.login',
    'width': 200,
    'height': 50,
    'longtitle': true,
    'theme': 'dark',
    'onsuccess': this. onSignIn
  });  
},
...

资料来源:https://developers.google.com/identity/sign-in/web/build-buttonhttps://github.com/meta-meta/webapp-template/blob/6d3e9c86f5c274656ef799263c84a228bfbe1725/app/Application/signIn.jsx

票数 35
EN

Stack Overflow用户

发布于 2019-07-31 05:36:57

我需要在一个功能组件中使用它,所以我想分享一下我是如何适应它的,我需要使用可以用来代替componentDidMount的useEffectHook

代码语言:javascript
复制
  useEffect(() => {
    window.gapi.signin2.render('g-signin2', {
      'scope': 'https://www.googleapis.com/auth/plus.login',
      'width': 200,
      'height': 50,
      'longtitle': true,
      'theme': 'dark',
      'onsuccess': onSignIn
    })
  })
票数 4
EN

Stack Overflow用户

发布于 2019-08-08 02:00:16

现在您可以使用这个封装了所有设置工作的React Google Login NPM包。您只能将选项传递给组件。

代码语言:javascript
复制
import React from 'react';
import ReactDOM from 'react-dom';
import GoogleLogin from 'react-google-login';
// or
import { GoogleLogin } from 'react-google-login';
 
 
const responseGoogle = (response) => {
  console.log(response);
}
 
ReactDOM.render(
  <GoogleLogin
    clientId="658977310896-knrl3gka66fldh83dao2rhgbblmd4un9.apps.googleusercontent.com"
    buttonText="Login"
    onSuccess={responseGoogle}
    onFailure={responseGoogle}
    cookiePolicy={'single_host_origin'}
  />,
  document.getElementById('googleButton')
);

代码来自程序包的文档。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31610461

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档