坚果大叔 坚果大叔
  • 首页
  • 闲言碎语
  • 技术
  • 生活
  • 记录
  • 朋友
  • 热点新闻
  • 常用代码
  • 工具箱
  • 关于
首页 › 技术 › React实现打字机效果~

React实现打字机效果~

坚果大叔
2023-08-22 17:31:49技术阅读 2,840

项目中有一个地方用到打字机的效果,并且在文字显示完成之后可以选择是否自动跳转到下一步骤。另外这个打字机效果在多个页面模块中使用,区别是打字完成后是否跳转。

核心代码

useEffect(() => {
    let currentIndex = 0;
    const interval = setInterval(() => {
      if (currentIndex < originalText.length - 1) {
        setText((prevText) => prevText + originalText[currentIndex]);
        currentIndex++;
      } else {
        clearInterval(interval);
        if (destination && destination.trim() !== '') {
          timerRef.current = window.setTimeout(() => {
            navigate(destination);
          }, 1000); // 在1秒后跳转到目标页面
        }
      }
    }, 100);

    return () => {
      clearInterval(interval);
      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
    };
}, [originalText, destination, navigate]);

在useEffect中,用了一个定时器来逐个字符地将原始文本添加到当前文本中。每100毫秒添加一个字符,直到添加完整个原始文本。然后,我们清除定时器以停止动画。另外引入了useHistory钩子来获取路由的history对象。在useEffect中,当打字机效果完成后,用setTimeout函数来延迟1秒后执行跳转操作。

如何使用

import React from 'react';
import Typewriter from './Typewriter';

const App: React.FC = () => {
  return (
    
); }; export default App;

其中 originalText 是需要打印的文本,destination 是文字打印完后需要跳转的页面。如果打印后停留当前页面则无需该参数。

实际效果

React实现打字机效果~-坚果大叔

完整代码

import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';

interface TypewriterProps {
  originalText: string;
  destination?: string;
}
const Typewriter: React.FC = ({ originalText, destination }) => {
    const [text, setText] = useState('');
    const navigate = useNavigate();
    const timerRef = useRef(null);

    ## 核心代码

    return (
        

{text}

); }; export default Typewriter;
赞赏 赞(2)
一晃又周三了
上一篇
镜头下的一点记录!
下一篇
在小程序中查看
搜你想看的
聚合文章
Flex布局入门
ant-design slider 组件增加推荐区间展示
iphone 利用 Scriptable 添加网上国网电费小组件
啊哦,全员核酸了。
闲言碎语
Memos
npm install 出现 Error:EISDIR:illegal operation on a directory 的错误提示!
2025-03-31 19:02:11
559 0 0
iphone 利用 Scriptable 添加网上国网电费小组件
2025-01-06 20:40:20
4,996 6 2
在博客中加上memos记录展示。
2024-12-25 23:41:27
2,329 5 2
网页点击平滑滚动效果~
2024-10-17 16:43:08
2,033 4
2
  • 2
博主

一位佛系的前端开发者,略通摄影,乐于尝试新事物,热衷于美食。

友链
故事胶片
公众号
坚果大叔 执行上下文 卖坚果的怪叔叔 Dacking
Copyright © 2017-2025 坚果大叔

开往-友链接力

萌ICP备20230818号

苏ICP备18048410号-3
  • 首页
  • 闲言碎语
  • 技术
  • 生活
  • 记录
  • 朋友
  • 热点新闻
  • 常用代码
  • 工具箱
  • 关于
# CSS # # JavaScript # # vue # # 微信 # # 生活 #
坚果大叔
317
文章
125
评论
365
喜欢