React中Google翻译组件重复显示问题求助
解决React中Google翻译组件重复显示语言栏的问题
看起来你遇到的问题是组件每次挂载时都会重复添加Google翻译脚本,且没有正确清理之前的翻译实例,导致多次初始化后出现多个语言选择栏。咱们一步步来修复这个问题:
问题根源
你的GoogleTranslate组件在componentDidMount里每次都会创建新的<script>标签并添加到body中,当组件卸载再重新挂载时(比如退出登录后回到首页),之前的脚本已经存在于页面中,同时window.googleTranslateElementInit被重新赋值,这会触发多次翻译元素初始化,最终导致多个语言栏出现。
修复方案
我们需要做这几件事:
- 避免重复添加翻译脚本
- 在组件卸载时清理翻译实例和全局变量
- 确保每次初始化前先移除旧的翻译元素
修改后的GoogleTranslate.js代码如下:
import React, { Component } from 'react'; class GoogleTranslate extends Component { componentDidMount() { // 先检查页面上是否已经存在Google翻译的脚本,避免重复添加 const existingScript = document.querySelector('script[src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"]'); if (!existingScript) { const addScript = document.createElement('script'); addScript.setAttribute('src', '//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit'); document.body.appendChild(addScript); } // 绑定初始化函数到window,同时确保每次初始化前先清理旧的翻译元素 window.googleTranslateElementInit = () => { // 先移除已有的翻译元素容器内容,防止重复创建 const translateContainer = document.getElementById('google_translate_element'); if (translateContainer) { translateContainer.innerHTML = ''; } /* eslint-disable no-new */ new window.google.translate.TranslateElement( { pageLanguage: 'pt', layout: window.google.translate.TranslateElement.FloatPosition.TOP_LEFT }, 'google_translate_element' ); }; // 如果脚本已经加载完成,手动触发初始化(防止脚本已加载但初始化函数没执行) if (window.google && window.google.translate) { window.googleTranslateElementInit(); } } componentWillUnmount() { // 组件卸载时清理全局变量和翻译实例 if (window.googleTranslateElementInit) { delete window.googleTranslateElementInit; } // 移除翻译容器的内容,清理DOM const translateContainer = document.getElementById('google_translate_element'); if (translateContainer) { translateContainer.innerHTML = ''; } } render() { return <div id="google_translate_element"></div>; } } export default GoogleTranslate;
关键修改说明
- 脚本重复添加检查:通过
querySelector判断脚本是否已存在,避免多次添加相同的script标签。 - 初始化前清理旧元素:在
googleTranslateElementInit里先清空翻译容器的内容,确保每次只创建一个TranslateElement实例。 - 组件卸载清理:在
componentWillUnmount中删除全局的初始化函数并清空翻译容器,防止组件卸载后残留的实例导致后续重复渲染。 - 手动触发初始化:如果脚本已经加载完成(比如第二次挂载组件时),直接调用初始化函数,确保翻译元素能正常渲染。
这样修改后,不管组件挂载多少次,都只会有一个语言选择栏显示啦。
内容的提问来源于stack exchange,提问作者alagumuthu.v
相关产品推荐
相关产品推荐

