如何为typed-react的React打字效果添加启动延迟?
实现带启动延迟的打字效果替代方案
下面给你几个实用的替代方案,不用纠结原库的限制:
方案1:用React状态延迟渲染typed-react组件
利用React的useState和setTimeout控制组件的渲染时机,等指定延迟时间到了再渲染打字组件:
import { useState, useEffect } from 'react'; import Typed from 'typed-react'; function DelayedTyped() { const [showTyped, setShowTyped] = useState(false); useEffect(() => { // 设置2秒延迟后显示打字组件 const timer = setTimeout(() => { setShowTyped(true); }, 2000); return () => clearTimeout(timer); }, []); return ( <div> {showTyped && <Typed strings={['Hello World', 'React Typing Effect']} typeSpeed={50} />} </div> ); }
方案2:手写自定义打字效果组件
完全自己实现,所有参数(包括启动延迟)都能自定义,灵活性拉满:
import { useState, useEffect } from 'react'; function CustomTyped({ strings, typeSpeed = 50, startDelay = 1000 }) { const [currentText, setCurrentText] = useState(''); const [currentStringIndex, setCurrentStringIndex] = useState(0); const [charIndex, setCharIndex] = useState(0); useEffect(() => { // 先执行启动延迟 const delayTimer = setTimeout(() => { const typeInterval = setInterval(() => { const currentString = strings[currentStringIndex]; if (charIndex < currentString.length) { setCurrentText(prev => prev + currentString[charIndex]); setCharIndex(prev => prev + 1); } else { clearInterval(typeInterval); // 可按需添加字符串切换、删除重打等逻辑 } }, typeSpeed); return () => clearInterval(typeInterval); }, startDelay); return () => clearTimeout(delayTimer); }, [strings, typeSpeed, startDelay, charIndex, currentStringIndex]); return <span>{currentText}</span>; } // 使用示例 <CustomTyped strings={['自定义打字效果', '支持启动延迟']} typeSpeed={60} startDelay={1500} />
方案3:替换为支持启动延迟的第三方库
比如react-typed(注意和typed-react不是同一个库),它原生支持startDelay配置项:
import Typed from 'react-typed'; function DelayedReactTyped() { return ( <Typed strings={['React Typed 原生支持延迟', '开箱即用']} typeSpeed={50} startDelay={2000} // 直接设置启动延迟,单位毫秒 /> ); }
内容的提问来源于stack exchange,提问作者Frecoder
相关产品推荐
相关产品推荐

