javascript - React TS - TypeWriter 组件
问题描述
所以我仍然在学习 React 和 JavaScript。我一直在尝试制作一个 TypeWriter 效果组件。我在网上找到了一个关于如何制作香草 JS TypeWriter 的教程,我正在尝试将其转换为 React 组件,我已经开始尝试将一些时间变量转换为道具,但我不是确定如何让它完全转换并一直在苦苦挣扎。
附加功能:
我也想做它,所以有一个prop
for 无限循环动画或只播放一次。例如:
loop={true}
将使它无限期地播放,如果您不指定此道具,它将只是通过数组进行动画处理,然后在数组中的最后一个单词处停止。
而不是 using classNames
,我想使用styled-components
,这可能会更好,因为闪烁的光标动画会发生一些动态的 className 东西。
我不确定本教程中的代码是否是编写这种逻辑的最有效方法,所以如果有改进的方法,请告诉我。:)
这是香草 JS TypeWriter 教程CodePen
这是目前我的组件中的内容:
import * as React from "react";
import styled from "styled-components";
interface ITypeWriter {
textArray: Array<string>;
typingDelay: number;
erasingDelay: number;
newTextDelay: number;
}
const TypeWriter: React.FC<ITypeWriter> = ({
textArray,
typingDelay,
erasingDelay,
newTextDelay
}) => {
// START - Code from tutorial
const typedTextSpan = document.querySelector(".typed-text");
const cursorSpan = document.querySelector(".cursor");
let textArrayIndex = 0;
let charIndex = 0;
function type() {
if (charIndex < textArray[textArrayIndex].length) {
if (!cursorSpan.classList.contains("typing"))
cursorSpan.classList.add("typing");
typedTextSpan.textContent += textArray[textArrayIndex].charAt(charIndex);
charIndex++;
setTimeout(type, typingDelay);
} else {
cursorSpan.classList.remove("typing");
setTimeout(erase, newTextDelay);
}
}
function erase() {
if (charIndex > 0) {
if (!cursorSpan.classList.contains("typing"))
cursorSpan.classList.add("typing");
typedTextSpan.textContent = textArray[textArrayIndex].substring(
0,
charIndex - 1
);
charIndex--;
setTimeout(erase, erasingDelay);
} else {
cursorSpan.classList.remove("typing");
textArrayIndex++;
if (textArrayIndex >= textArray.length) textArrayIndex = 0;
setTimeout(type, typingDelay + 1100);
}
}
document.addEventListener("DOMContentLoaded", function() {
if (textArray.length) setTimeout(type, newTextDelay + 250);
});
// END - Code from tutorial
return (
<div className="App">
<StyledText>{}</StyledText>
</div>
);
};
export default TypeWriter;
const StyledText = styled.span`
font-weight: normal;
color: #dd7732;
`;
这是一个CodeSandBox,感谢分叉 :)
解决方案
推荐阅读
- javascript - 正确发送后如何重置 JSON?
- interface - 与石墨烯后端反应阿波罗中 graphql 接口类型的常见字段
- excel - 复制粘贴循环 vba - 覆盖当前单元格
- python - 在循环中为多个输入创建元音变量
- python - 迭代工具 Python
- python - 熊猫连接上一个当前和下一个文本
- python - 如何在 FiPy 中编写具有自变量的方程项?
- r - 使用 R veriosn 3.6.1 以 csv 格式导入数字数据的问题
- android - 在 Android\Sdk 中找不到带有哈希字符串“android-28”的目标
- rust - 如何给 impl trait 起别名?