如何修改Google登录按钮语言?@react-oauth/google技术求助
解决方案
1. 切换为弹窗登录模式
要实现弹窗登录,有两种可行方式:
方式一:修改GoogleLogin组件配置
直接给组件添加ux_mode="popup"属性,明确指定弹窗模式:
<GoogleLogin onSuccess={(credentialResponse) => onSuccess(credentialResponse)} onError={() => onFailure("")} text='continue_with' locale={i18n.language} logo_alignment='center' ux_mode="popup" // 新增弹窗模式配置 />
方式二:用useGoogleLogin钩子自定义触发逻辑
如果需要更灵活的触发逻辑(比如绑定自定义按钮),可以使用useGoogleLogin钩子,它默认采用弹窗模式:
import { useGoogleLogin, CredentialResponse } from '@react-oauth/google'; const GoogleLoginButton = ({ onSuccess, onFailure }: Props) => { const { t, i18n } = useTranslation(); const login = useGoogleLogin({ onSuccess: (response) => { onSuccess(response as unknown as CredentialResponse); }, onError: () => onFailure(""), ux_mode: "popup", locale: i18n.language, }); return ( <button onClick={login}> {t('continue_with_google')} </button> ); };
2. 修复登录按钮语言不生效问题
按钮始终显示西班牙语,核心原因是语言代码格式不匹配或Google脚本未加载对应语言资源:
步骤1:校验语言代码格式
Google支持ISO 639-1标准语言代码(比如意大利语为it,阿根廷西班牙语为es-AR),检查你的i18n配置,确保i18n.language输出的是符合要求的代码。如果返回的是带地区后缀的格式(如it-IT),可以截取前缀使用:
const googleLocale = i18n.language.split('-')[0]; <GoogleLogin // 其他属性 locale={googleLocale} />
步骤2:全局指定Google脚本语言
在加载Google OAuth客户端脚本时,通过hl参数强制指定语言(修改index.html中的脚本标签):
<script src="https://accounts.google.com/gsi/client" async defer hl="it"></script>
该设置会覆盖组件的locale属性,适合全局统一语言的场景。
3. 从useGoogleLogin获取id_token
默认情况下useGoogleLogin返回access_token,要获取后端需要的id_token,需在钩子配置中指定response_type和必要的scope:
const login = useGoogleLogin({ onSuccess: (response) => { const tokenId = response.id_token; // 适配原有onSuccess的参数格式 onSuccess({ credential: tokenId } as CredentialResponse); }, onError: () => onFailure(""), response_type: "id_token", // 必须指定该参数以获取id_token scope: "openid email profile", // openid是获取id_token的必要权限 ux_mode: "popup", });
如果同时需要access_token,可将response_type设置为"token id_token"。
内容的提问来源于stack exchange,提问作者Franco Brizuela
相关产品推荐
相关产品推荐

