admin管理员组

文章数量:1667083

方法一:

import React, { useState, useEffect, useRef } from 'react';

const Typewriter = ({ text, speed }) => {
  const [displayText, setDisplayText] = useState('');
  const [isPaused, setIsPaused] = useState(false);
  const [isTextFinished, setIsTextFinished] = useState(false);
  const currentIndexRef = useRef(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      if (!isPaused) {
        setDisplayText((prevText) => {
          if (currentIndexRef.current < text.length) {
            return prevText + text[currentIndexRef.current++];
          } else {
            clearInterval(intervalId);
            setIsTextFinished(true);
            return prevText;
          }
        });
      }
    }, speed);

    return () => clearInterval(intervalId);
  }, [text, speed, isPaused]);

  const handlePauseResume = () => {
    setIsPaused((prevPaused) => !prevPaused);
    if (!isPaused) {
      currentIndexRef.current = currentIndexRef.current;
    }
  };

  return (
    <div>
      <div>{displayText}</div>
      {!isTextFinished && (
        <button onClick={handlePauseResume}>
          {isPaused ? '继续' : '暂停'}
        </button>
      )}
    </div>
  );
};

const App = () => {
  const textToType = '请问,您是否需要帮助?我是一名程序员,您需要什么帮助?';
  const typingSpeed = 100;

  return (
    <div>
      <Typewriter text={textToType} speed={typingSpeed} />
    </div>
  );
};

export default App;

方法二: 参考这个

使用插件 typed.js  Typed.js - Type your heart out

react 实现chatGPT的打印机效果 兼容富文本,附git地址_前端实现chartgpt打印机效果react-CSDN博客

本文标签: 打印机类似效果ReactchatGPT