React实现打字机效果~
戳上方“执行上下文”,选择“置顶公众号”
关键时刻,第一时间送达!
核心代码
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]);
如何使用
import React from 'react';
import Typewriter from './Typewriter';
const App: React.FC = () => {
return (
<div>
<Typewriter originalText="Hello, World!" destination="/other-page" />
</div>
);
};
export default App;
其中 originalText 是需要打印的文本,destination 是文字打印完后需要跳转的页面。如果打印后停留当前页面则无需该参数。
实际效果
完整代码
import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
interface TypewriterProps {
originalText: string;
destination?: string;
}
const Typewriter: React.FC<TypewriterProps> = ({ originalText, destination }) => {
const [text, setText] = useState('');
const navigate = useNavigate();
const timerRef = useRef<number | null>(null);
## 核心代码
return (
<div className="typewriter">
<h1>{text}</h1>
</div>
);
};
export default Typewriter;
图片分享
前端公众号和交流群
评论