You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS中Typed.js异常:文本闪烁、双光标问题求助

React中使用Typed.js出现双光标和文本闪烁的解决方法

你的问题源于重复创建Typed实例和未正确清理实例,结合React组件生命周期特性,以下是具体修复方案:

问题代码回顾

import React from "react";
import Typed from "typed.js";

class SkillsList extends React.Component{
    componentDidMount(){
        new Typed('#skills', {
            strings: ['Front End Developer','Full Stack Developer', 'Chrome Extension Developer', 'Web Scraping and Automation', 'PHP Developer', 'Python Developer'],
            typeSpeed: 75,
            loop: true
        });
    }
    render(){
        return (
            <span id="skills"/>
        );
    }
}

export default SkillsList;

问题表现:
Glitched Text and Double Cursor

修复步骤及代码

核心优化点

  • 用React Ref替代全局ID选择器,避免跨组件DOM选择冲突
  • 保存Typed实例引用,组件卸载时销毁实例,防止内存泄漏和重复实例

修改后的代码:

import React from "react";
import Typed from "typed.js";

class SkillsList extends React.Component {
  // 存储Typed实例引用
  typedInstance = null;
  // 创建React Ref绑定DOM元素
  skillsRef = React.createRef();

  componentDidMount() {
    // 通过Ref获取DOM元素,初始化Typed实例
    this.typedInstance = new Typed(this.skillsRef.current, {
      strings: [
        'Front End Developer',
        'Full Stack Developer',
        'Chrome Extension Developer',
        'Web Scraping and Automation',
        'PHP Developer',
        'Python Developer'
      ],
      typeSpeed: 75,
      loop: true
    });
  }

  componentWillUnmount() {
    // 组件卸载时销毁Typed实例,清理资源
    if (this.typedInstance) {
      this.typedInstance.destroy();
    }
  }

  render() {
    // 用Ref绑定span元素,避免自闭合标签的渲染异常
    return <span ref={this.skillsRef}></span>;
  }
}

export default SkillsList;

改动说明

  • 放弃全局ID选择器,改用React.createRef()精准获取当前组件内的DOM元素,避免重复实例问题
  • 在componentWillUnmount生命周期中调用destroy()方法,确保组件卸载时清理Typed实例,防止内存泄漏
  • 将自闭合<span id="skills"/>改为标准闭合标签<span ref={this.skillsRef}></span>,规避部分渲染环境下的异常

内容的提问来源于stack exchange,提问作者Ra Zi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 09:01:17