首页 > 解决方案 > 如何为我的打字机效果插入新行

问题描述

我用 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 个连续的文本块,但是当当前数组项完成时,我无法让它插入新行。

有人可以告诉我我应该做什么。

谢谢!

标签: javascriptreactjstypescript

解决方案


我很想每次都创建一个新的文本数组,其中包含迄今为止显示的所有内容。使用 for 循环应该很容易做到这一点。

然后只需使用传统的反应映射方法渲染这个(部分)文本数组结构。

此 CodeSandbox演示了该方法。


推荐阅读