首页 > 解决方案 > React TS - TypeWriter 组件

问题描述

所以我仍然在学习 React 和 JavaScript。我一直在尝试制作一个 TypeWriter 效果组件。我在网上找到了一个关于如何制作香草 JS TypeWriter 的教程,我正在尝试将其转换为 React 组件,我已经开始尝试将一些时间变量转换为道具,但我不是确定如何让它完全转换并一直在苦苦挣扎。

附加功能: 我也想做它,所以有一个propfor 无限循环动画或只播放一次。例如: 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,感谢分叉 :)

标签: javascriptreactjstypescriptstyled-components

解决方案


推荐阅读