React 18中使用react-typical动画不流畅及react-type-animation报错求助
React 18 下 react-typical 动画不流畅及 react-type-animation 导入错误的解决办法
一、解决 react-typical 在 React 18 中动画卡顿的问题
react-typical 本身未适配 React 18 的并发渲染机制,强制安装必然会出现兼容性问题,不想降级 React 的话,有两个可行方案:
改用社区维护的 React 18 适配版:
react-typical-react18
先卸载原库,再安装适配版:npm uninstall react-typical npm install react-typical-react18代码用法和原库完全一致,仅需替换导入路径:
import Typical from 'react-typical-react18'; // 原有代码可直接复用 <h1> {" "} <Typical loop={Infinity} steps={[ "Enthusiastic Dev 😎", 1000, "Full Stack Devloper 👨💻", 1000, "MERN Stack Dev 🌐", 1000, "Java Enthusiast 🔥", 1000, "React Developer 🎆", 1000, ]} /> </h1>手动封装轻量打字动画组件
用 React 原生的useState和useEffect实现,完全适配 React 18,还能自定义动画速度:import { useState, useEffect } from 'react'; const TypingAnimation = ({ steps, loop = Infinity }) => { const [currentStepIdx, setCurrentStepIdx] = useState(0); const [displayText, setDisplayText] = useState(''); const [charIdx, setCharIdx] = useState(0); useEffect(() => { if (currentStepIdx >= steps.length) { if (loop > 0) { setCurrentStepIdx(0); setCharIdx(0); setDisplayText(''); } return; } const currentItem = steps[currentStepIdx]; if (typeof currentItem === 'string') { // 打字阶段 if (charIdx < currentItem.length) { const timer = setTimeout(() => { setDisplayText(prev => prev + currentItem[charIdx]); setCharIdx(prev => prev + 1); }, 100); // 数字越小打字越快,可自行调整 return () => clearTimeout(timer); } else { // 文本停留阶段,切换到下一个时间步 const timer = setTimeout(() => { setCurrentStepIdx(prev => prev + 1); setCharIdx(0); setDisplayText(''); }, steps[currentStepIdx + 1]); return () => clearTimeout(timer); } } else { // 跳过时间步,直接进入下一个文本 setCurrentStepIdx(prev => prev + 1); } }, [currentStepIdx, charIdx, steps, loop]); return <span>{displayText}</span>; }; // 使用方式和原有代码一致 <h1> {" "} <TypingAnimation loop={Infinity} steps={[ "Enthusiastic Dev 😎", 1000, "Full Stack Devloper 👨💻", 1000, "MERN Stack Dev 🌐", 1000, "Java Enthusiast 🔥", 1000, "React Developer 🎆", 1000, ]} /> </h1>
二、解决 react-type-animation 中 "TypeAnimation not found" 的错误
这个问题基本是导入方式错误或版本不兼容导致的,按以下步骤处理:
- 先确保安装适配 React 18 的最新版:
npm install react-type-animation - 最新版采用默认导出,且参数名有调整(
sequence替代steps,repeat替代loop),正确使用代码:import TypeAnimation from 'react-type-animation'; <h1> {" "} <TypeAnimation sequence={[ "Enthusiastic Dev 😎", 1000, "Full Stack Devloper 👨💻", 1000, "MERN Stack Dev 🌐", 1000, "Java Enthusiast 🔥", 1000, "React Developer 🎆", 1000, ]} repeat={Infinity} /> </h1>
如果安装的是旧版,可能需要用命名导入import { TypeAnimation } from 'react-type-animation';,但旧版大概率不兼容 React 18,优先推荐安装最新版。
内容的提问来源于stack exchange,提问作者Jaydeep Chouhan
相关产品推荐
相关产品推荐

