Sti*_*rud 16 reactjs google-signin google-identity
我正在使用Google Identity 中的“使用 Google 登录”按钮。我已将此按钮文档页面中的 HTML放入 React 组件中。看起来像这样:
export default function GoogleLoginButton() {
return (
<>
<div
id="g_id_onload"
data-client_id="XXXXXX"
data-auto_prompt="false"
></div>
<div
className="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>
</>
);
}
Run Code Online (Sandbox Code Playgroud)
第一次加载页面时,Google 登录按钮正确显示,我可以登录。然后登录按钮被注销按钮取代。问题是,当我单击应该再次呈现 Google 登录按钮的注销按钮时,它不会重新出现!这是为什么?
我可以补充一点,注销后刷新页面会返回 Google 按钮。
Ale*_*dón 11
正如 Stian 所说,一旦应用程序呈现,谷歌脚本就会注入谷歌按钮。问题是,如果您重新渲染按钮所在的组件,它将消失,因为 google 脚本已经执行,并且不会在将来的重新渲染中执行(它不会再次注入 google 按钮)。
另一种解决方案是在 useEffect 内调用window.google.accounts.id.renderButton ,该 useEffect 应放置在重新渲染的组件内。这将在每次调用 useEffect 时重新注入 google 按钮(重新渲染组件)。
该方法接收的第一个参数renderButton应该是对 div 的引用,google 脚本将在该 div 内注入登录按钮。
注意:请记住首先调用google.accounts.id.initialize初始化 google 脚本
这是例子:
const divRef = useRef(null);
useEffect(() => {
if (divRef.current) {
window.google.accounts.id.initialize({
client_id: <YOUR_CLIENT_ID_GOES_HERE>,
callback: (res, error) => {
// This is the function that will be executed once the authentication with google is finished
},
});
window.google.accounts.id.renderButton(divRef.current, {
theme: 'filled_blue',
size: 'medium',
type: 'standard',
text: 'continue_with',
});
}
}, [divRef.current]);
return (
{/* Other stuff in your component... */}
{/* Google sign in button -> */} <div ref={divRef} />
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8720 次 |
| 最近记录: |