使用 React 为代码块创建打字机效果

使用打字机效果,单词一次显示一个字母,而不是一次显示所有单词,使文本看起来好像是实时书写的。您可以在Codepen 的登录页面上找到代码块打字机效果的示例,该示例使用语法高亮(一种特殊的颜色格式)来轻松地以代码的形式显示书面文本。

在本文中,我们将学习如何使用 React 从头开始构建类似的代码块打字机效果。我们还将演示一种使用预先存在的打字机包的替代方法。要学习本教程,您需要具备 React 的基本知识。我们将介绍以下内容:

  • 安装依赖项

  • 打造打字机效果

    • 打字机展示区

    • 添加闪烁的光标

  • 将打字机效果添加到文本

  • 删除和重新输入文本

  • 高亮代码语法

  • 使用打字库

您可以在此 GitHub 存储库中找到本教程的完整源代码。让我们开始吧!

安装依赖项

如果您还没有安装 React,请在您的系统中导航到您的项目目录,打开一个命令行窗口,然后在其中运行以下 bash 脚本:

npx create-react-app typewriter

上面的命令创建了一个 React 项目文件夹,该文件夹调用typewriter了构建我们的应用程序所需的所有依赖项。为了轻松设计我们的应用程序,我们将使用 Tailwind CSS。您可以通过在 CLI 中运行以下命令来安装 Tailwind CSS:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

安装完成后,修改tailwind.config.js文件以允许支持jsx元素,如下所示:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

最后,将以下 Tailwind CSS 指令添加到 的顶层index.css:

@tailwind base;
@tailwind components;
@tailwind utilities;

打造打字机效果

我们的打字机效果将由两个主要部分组成,一个用于保存我们想要动画的文本的容器和一个用于模仿打字机的闪烁光标。

打字机展示区

首先,在我们的 App.js文件中,我们将构建打字机效果的显示窗口:

import "./App.css";
import {React, useState, useEffect} from "react";
​
function App() {
  const [text1, setText1] = useState("const sayHello = () = {");
  const [text2, setText2] = useState("Console.log('hello')");
  const [text3, setText3] = useState("//This prints out Hello World");
  return (
    <div className=" flex h-screen justify-center items-center">
      <div className=" h-1/2 w-1/2 bg-black rounded-md flex items-center pl-6">
        {/* type writer display */}
        <span>
          <div className=" text-white text-2xl blinking-cursor">{text1}</div>
          <div className=" text-white text-2xl blinking-cursor">{text2}</div>
          <div className=" text-white text-2xl blinking-cursor">{text3}</div>
          <div className=" text-white text-2xl blinking-cursor">{`}`}</div>
        </span>
      </div>
    </div>
  );
}
​
export default App;

上面的代码创建了一个容器,我们将在其中保存要使用打字机效果制作动画的文本。如果我们用npm start命令运行上面的代码,我们会得到一个“Hello, World!” 结果类似于下图:

添加闪烁的光标

接下来,我们将构建一个闪烁的光标并将其附加到文本的结尾。将以下代码添加到index.css:

.bg-code{
  background-color: rgb(40, 42, 54);
}
​
.blinking-cursor::after {
  content: "|";
  animation: blink 1s step-end infinite;
}
@keyframes blink {
  from,
  to {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}

上面的 CSS 样式在|每个文本的末尾添加一个,从而产生模仿光标的闪烁效果。

将打字机效果添加到文本

为了创建我们的打字机效果,我们将使用 React useEffectHook。为此,请将以下修改添加到您的代码中:

const first_text = "const sayHello = () = {";
  const second_text = "console.log('hello')";
  const third_text = "//This prints out Hello World";
​
  const [text1, setText1] = useState("");
  const [text2, setText2] = useState("");
  const [text3, setText3] = useState("");
​
  useEffect(() => {
    const timeout = setTimeout(() => {
      setText1(first_text.slice(0, text1.length + 1));
    }, 100);
    return () => clearTimeout(timeout);
  }, [text1]);
​
  useEffect(() => {
    const timeout = setTimeout(() => {
      setText2(second_text.slice(0, text2.length + 1));
    }, 250);
​
    return () => clearTimeout(timeout);
  }, [text2]);
​
  useEffect(() => {
    const timeout = setTimeout(() => {
      setText3(third_text.slice(0, text3.length + 1));
    }, 300);
​
    return () => clearTimeout(timeout);
  }, [text3]);

在上面的代码中,我们使用了一个setTimeout函数和一个切片运算符。该setTimeout函数在指定的时间间隔后执行代码块。我们使用拼接运算符将整个字符串分成字符,并一次返回一个字符。

对于回调,我们使用状态。每次我们输入一个新字符时,状态都会更新,setTimeout函数就会被执行。结果,setTimeout运行直到整个文本被完全键入。

彩云小梦AI写作软件,自动续写的AI工具,多种写作风格任意切换!

删除和重新输入文本

为了循环打字机效果,我们将添加两个状态,isdeleting和istyping,分别用于用户想要删除文本和完成打字时:

const textState = ["istyping", "isdeleting"];
const [typing, setTyping] = useState(textState[0]);
​
function sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
}

现在我们已经创建了用于输入和删除文本的状态,让我们使用该sleep函数来创建从两种状态切换之间的延迟。因此,当用户完全键入文本时,我们将实现暂停。让我们继续修改我们的代码以使用这些状态,如下所示:

useEffect(() => {
    const timeout = setTimeout(() => {
      if (typing === "istyping" && text1 !== first_text) {
        setText1(first_text.slice(0, text1.length + 1));
      }
      else if (text1 === first_text && typing === "istyping"){
        sleep(2000).then(()=>{
        setTyping(textState[1])
        })
      }
      else if ( (text1 === first_text && typing==="isdeleting") || typing === "isdeleting" ) {
        setText1(first_text.slice(0, text1.length - 1));
        if(text1.length<=2){
            setTyping(textState[0])
        }
      }
    }, 100);
  return () => clearTimeout(timeout);
}, [text1, typing1]);

在上面的代码中,我们检查typing等于istyping并且文本不等于完整的字符串。如果返回true,我们将运行打字效果。当文本类似于完整的字符串时,我们使用该函数在两秒后sleep切换到状态。isdeleting

最后,我们使用最后一个条件一次删除一个字符,直到只剩下一个字母。至此,typing状态恢复为istyping,整个过程重新开始。我们也会为text2and做同样的事情text3。

高亮代码语法

为了使我们的文本看起来像一个代码块,我们将 通过 CLI安装React Syntax Highlighter :

npm i react-syntax-highlighter

安装好这个包后,我们可以导入进去App.js使用,如下:

import SyntaxHighlighter from 'react-syntax-highlighter';
import { docco } from 'react-syntax-highlighter/dist/esm/styles/hljs';
//...
<span>
  <div className=" text-2xl">
    <SyntaxHighlighter className="blinking-cursor" language="javascript" style={dracula}>
      {text1}
    </SyntaxHighlighter>
  </div>
  <div className=" text-2xl">
    <SyntaxHighlighter className="blinking-cursor" language="javascript" style={dracula}>
      {text2}
    </SyntaxHighlighter>
  </div>
  <div className=" text-2xl">
    <SyntaxHighlighter className="blinking-cursor" language="javascript" style={dracula}>
      {text3}
    </SyntaxHighlighter>
  </div>
  <div className=" text-2xl">
    <SyntaxHighlighter className="blinking-cursor" language="javascript" style={dracula}>
      {`}`}
    </SyntaxHighlighter>
  </div>
</span>

现在我们已经实现了我们的 Syntax Higlighter组件,我们可以包装我们的打字机效果。

使用预建的打字库

作为编码和自定义我们自己的打字机效果的替代方案,我们可以使用预构建的库来节省时间。

处理打字机效果的库的一个示例是react-typewriter-effect. 我们可以通过 CLI 使用以下命令安装此软件包:

npm i react-typewriter-effect

安装完成后,我们可以在我们的应用程序中使用它来获得打字机效果:

import TypeWriterEffect from 'react-typewriter-effect';
//...
​
<TypeWriterEffect
  textStyle={{ fontFamily: 'Red Hat Display' }}
  startDelay={100}
  cursorColor="black"
  text="Text for typewriting effect here"
  typeSpeed={100}
  eraseSpeed={100}
/>

上面的代码将为指定的文本字符串产生打字机效果。

结论

在本文中,我们学习了如何使用 React 轻松创建打字机效果。在您的网站或应用程序中实施此功能可以通过增加视觉兴趣并将用户的注意力引导到您想要的位置来改进您的 UI。您可以添加到我们从头开始构建的打字机效果以实现更多您自己的自定义,或者您可以使用为您实现此功能的库,例如react-typewriter-effect