React實現(xiàn)打字機效果~
戳上方“執(zhí)行上下文”,選擇“置頂公眾號”
關(guān)鍵時刻,第一時間送達!
核心代碼
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秒后跳轉(zhuǎn)到目標頁面
}
}
}, 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 是文字打印完后需要跳轉(zhuǎn)的頁面。如果打印后停留當前頁面則無需該參數(shù)。
實際效果

完整代碼
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;
圖片分享
前端公眾號和交流群

評論
圖片
表情
