javascript - 如何为我的打字机效果插入新行
问题描述
我用 React Hooks 和 Typescript 组合了一个基本的打字机效果。
const TypingText: React.FunctionComponent = () => {
const [index, setIndex] = useState(0);
const [subIndex, setSubIndex] = useState(0);
const text = ["Line 1", "Line 2.", "Line 3.", "Line 4"]
useEffect(() => {
const timeout = setTimeout(() => {
setSubIndex((prev) => prev + 1);
}, 100);
if (subIndex === text[index].length) {
setSubIndex(0);
setIndex((prev) => prev + 1)
}
return () => clearTimeout(timeout);
}, [subIndex]);
const renderText = () => {
let htmlArray: JSX.Element[] = [];
if (subIndex === text[index].length) {
htmlArray.push(<br />)
} else {
htmlArray.push(<p>{text[index].substring(0, subIndex)}</p>)
}
return htmlArray
};
return (
<h1>
{renderText()}
</h1>
)
};
这适用于 1 个连续的文本块,但是当当前数组项完成时,我无法让它插入新行。
有人可以告诉我我应该做什么。
谢谢!
解决方案
我很想每次都创建一个新的文本数组,其中包含迄今为止显示的所有内容。使用 for 循环应该很容易做到这一点。
然后只需使用传统的反应映射方法渲染这个(部分)文本数组结构。
此 CodeSandbox演示了该方法。
推荐阅读
- fonts - 在日文版 Windows 上使用扩展 ASCII 字符(字符 > 127)时出现剪贴板问题
- c# - 拦截和更改应用程序生成的 sql 查询
- spring - Spring框架中@PropertySource和@DynamicPropertySource的区别
- javascript - 如何将 cshtml 文件中的布尔值传递给 javascript 函数/构造函数?
- java - Java 中的优先级队列(最大堆声明)
- r - 如何使用 R 中预先计算的置信区间使用 geom_smooth 制作平滑置信带/功能区
- apache-kafka - 无法将 MongoDB 作为源连接到 Kafka
- php - 使用 Laravel 对一对多(多态)关系进行排序
- c++ - UE4 playfab 委托因 Null 自定义数据而崩溃
- docusignapi - 多个文档和签名者,嵌入式签名中的文档顺序不正确