欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

由于很难在网络上找到 React 访问,谷歌登录只能自己写点东西

最编程 2024-04-29 17:55:05
...
constructor(props) { super(props); this.loadGoogleJS(); // 将回调函数放在windoe里,让谷歌获取到,否则无效 // 注意!需要指向当前组件this,这样可以使用组件下的其他方法 // 如果使用其他方式就可以不用这么麻烦,例如使用一键式js API(官方文档有介绍) window.handleCredentialResponse = this.handleCredentialResponse.bind(this); } loadGoogleJS() { const styleTag = document.createElement('script'); styleTag.src = `https://accounts.google.com/gsi/client`; styleTag.async = true; styleTag.defer = true; document.head.appendChild(styleTag); } // 回调函数 handleCredentialResponse(value) { console.log('google login', value); this.loginByIdToken(value.credential); this.setState({ IdToken: value.credential || null, }); } ... render(){ <div id="g_id_onload" data-client_id="YOUR_GOOGLE_CLIENT_ID" // data-login_uri="https://your.domain/your_login_endpoint" data-callback="handleCredentialResponse" // 传入回调函数的字符串 data-auto_prompt="false"> </div> <div class="g_id_signin" data-type="standard" data-size="large" data-theme="outline" data-text="sign_in_with" data-shape="rectangular" data-logo_alignment="left"> </div> }