使用谷歌登录按钮与反应

Thi*_*ico 35 javascript reactjs google-signin

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

我可能错过了一些反应但我无法找到它.有帮助吗?在下面找到加载所有内容和组件本身的html.

<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" />
        );
    }
});
Run Code Online (Sandbox Code Playgroud)

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

Bra*_*ugh 29

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

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
  });  
},
...
Run Code Online (Sandbox Code Playgroud)

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


Max*_*oll 5

我需要在功能组件中使用它,所以我想分享我如何调整它,我需要使用 useEffectHook ,它可以用来代替 componentDidMount

  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
    })
  })
Run Code Online (Sandbox Code Playgroud)

  • 我尝试了你的代码,但是“onsuccess”没有被触发。还需要什么其他设置吗? (3认同)
  • 通过使用基于 https://developers.google.com/identity/sign-in/web/reference 的 **GoogleAuth.isSignedIn.listen()** 解决了我的问题。它就像这样 `window.gapi.load('auth2', () =&gt; { const auth2 = window.gapi.auth2.init({ config 位于此处 }); auth2.isSignedIn.listen(() =&gt; { your代码在这里 }) })` 。如果您想获取用户个人资料,可以使用 **GoogleUser.getBasicProfile()**。希望这可以帮助。 (2认同)