跳到主要内容

打字机

一个简单的 React 打字机效果小组件

效果演示

|

信息

可参考 TypeWriter 一文,详细介绍了该组件是如何实现的

完整代码

TypeWriter.tsx
import React, { useEffect, useState } from "react";
import "./TypeWriter.css";

const SEPERATOR = ";";
const INTERVAL = 3000;
const TYPING_SPEED = 30;

function Typewriter({
text,
textSeparator = SEPERATOR,
typingSpeed = TYPING_SPEED,
delinterval = INTERVAL,
}) {
const texts = text.split(textSeparator);
const [displayText, setDisplayText] = useState("");
const [textIndex, setTextIndex] = useState(0);
const [isDeleting, setIsDeleting] = useState(false);
const [isTypingFinished, setIsTypingFinished] = useState(false);

useEffect(() => {
const currentText = texts[textIndex];
let interval;

if (isDeleting) {
interval = setInterval(() => {
setDisplayText((prevText) => prevText.slice(0, -1));
if (displayText.length === 0) {
clearInterval(interval);
setIsDeleting(false);
setIsTypingFinished(false);
setTextIndex((prevIndex) => (prevIndex + 1) % texts.length);
}
}, typingSpeed / 3);
} else if (isTypingFinished) {
interval = setTimeout(() => {
setIsDeleting(true);
}, delinterval);
} else {
interval = setInterval(() => {
if (displayText.length < currentText.length) {
setDisplayText(
(prevText) => prevText + currentText[displayText.length]
);
} else {
clearInterval(interval);
setIsTypingFinished(true);
}
}, typingSpeed);
}

return () => {
clearInterval(interval);
};
}, [
texts,
typingSpeed,
displayText,
isDeleting,
isTypingFinished,
textIndex,
]);

return (
<div className="typewriter">
<span>{displayText}</span>
<span className="cursor">|</span>
</div>
);
}

export default Typewriter;
请作者喝可乐🥤:
本文遵循 CC 4.0 BY-SA 版权协议,转载请标明出处