react实现圆球打字
实现思路
使用React实现圆球打字效果,可以通过结合CSS动画和JavaScript控制字符的逐字显示。核心思路是创建一个圆形组件,内部动态显示文字,通过状态管理控制当前显示的字符。
代码实现
安装必要的依赖(如需要):
npm install styled-components
组件代码
import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
const CircleContainer = styled.div`
width: 200px;
height: 200px;
border-radius: 50%;
background-color: #3498db;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 24px;
font-weight: bold;
`;
const TypingText = styled.span`
white-space: pre-wrap;
`;
const CircleTyping = ({ text, speed = 150 }) => {
const [displayText, setDisplayText] = useState('');
useEffect(() => {
let currentIndex = 0;
const intervalId = setInterval(() => {
if (currentIndex <= text.length) {
setDisplayText(text.substring(0, currentIndex));
currentIndex++;
} else {
clearInterval(intervalId);
}
}, speed);
return () => clearInterval(intervalId);
}, [text, speed]);
return (
<CircleContainer>
<TypingText>{displayText}</TypingText>
</CircleContainer>
);
};
export default CircleTyping;
使用示例
import React from 'react';
import CircleTyping from './CircleTyping';
function App() {
return (
<div className="App">
<CircleTyping text="Hello, World!" speed={100} />
</div>
);
}
export default App;
自定义选项
- 调整速度:通过
speed属性控制打字速度(毫秒) - 样式修改:在
CircleContainer中修改圆形样式(颜色、大小等) - 文本换行:使用
white-space: pre-wrap保持文本格式
高级扩展
-
光标效果:添加闪烁的光标动画
&::after { content: '|'; animation: blink 1s infinite; } @keyframes blink { 0%, 100% { opacity: 1; } 50% { opacity: 0; } } -
多行文本:通过计算文本宽度自动换行
-
完成回调:添加
onComplete属性在打字结束时触发函数
注意事项
- 确保父容器有足够空间显示圆形组件
- 长文本可能需要调整圆形尺寸或字体大小
- 清除定时器防止内存泄漏(已在useEffect中处理)







