taro-typeit
Version:
A custom typeit component for Taro + React
135 lines (99 loc) • 4.33 kB
Markdown
# taro-typeit
**注:本项目80%由chatGPT生成**
一个基于 **Taro + React** 的小程序/H5 自定义打字机效果实用组件。
> 适用于 Taro 3+ 项目,React 17/18。
## ✨ 特性
- ✅ 打字机效果:支持字符串和 JSX 元素混合显示
- ✅ 打字速度可配置:`speed` 与 `deleteSpeed`
- ✅ 支持循环播放 `loop` 与删除模式 `deleteMode`
- ✅ 可控制光标显示 `cursor` 与闪烁
- ✅ 支持开始延迟 `startDelay` 与停顿延迟 `breakDelay`
- ✅ 保留已打字内容 `keepAll`
- ✅ TypeScript 完整类型定义
## 📦 安装
```bash
# 安装组件包
npm install taro-typeit
# 确保项目已有依赖
npm install react @tarojs/components @tarojs/taro
```
> 样式需要单独引入(或让打包产物自动引入):
```ts
import 'taro-typeit/dist/index.css';
```
## 🔨 快速上手
```tsx
import React from 'react';
import { View } from '@tarojs/components';
import TypeIt from 'taro-typeit';
const App: React.FC = () => {
return (
<View>
<TypeIt
strings={[
'Hello, world!',
<View style={{ color: 'red' }}>This is JSX content!</View>,
'Welcome to Taro + React!',
]}
speed={120}
deleteSpeed={60}
loop
keepAll
cursor
startDelay={500}
breakDelay={1000}
onStringComplete={index => console.log('String complete:', index)}
onComplete={() => console.log('All strings complete!')}
/>
</View>
);
};
export default App;
```
## 🧩 组件属性(Props)
| 属性名 | 类型 | 必填 | 默认值 | 说明 | |
| ------------------ | ------------------------- | ---------------- | ------- | --------------- | ----------------- |
| `strings` | \`(string | JSX.Element)[]\` | ✔️ | `[]` | 要显示的字符串或 JSX 元素数组 |
| `speed` | `number` | ✖️ | `100` | 打字速度(毫秒/字符) | |
| `deleteSpeed` | `number` | ✖️ | `50` | 删除速度(毫秒/字符) | |
| `breakDelay` | `number` | ✖️ | `1000` | 打完一条字符串后的停顿时间 | |
| `loop` | `boolean` | ✖️ | `false` | 是否循环播放 | |
| `cursor` | `boolean` | ✖️ | `true` | 是否显示光标 | |
| `keepAll` | `boolean` | ✖️ | `true` | 是否保留已打过的内容 | |
| `deleteMode` | `boolean` | ✖️ | `false` | 打完后是否删除文字再继续下一条 | |
| `startDelay` | `number` | ✖️ | `0` | 初始开始延迟 | |
| `onStringComplete` | `(index: number) => void` | ✖️ | — | 每条字符串完成回调 | |
| `onComplete` | `() => void` | ✖️ | — | 所有字符串完成回调 | |
## 🌏 使用注意事项
- JSX 元素不会有打字动画,会直接显示完整内容。
- 光标仅在当前打字的字符串上闪烁。
- `loop` 为 `true` 时,打完最后一条字符串会重头开始。
- 配合 `deleteMode` 可实现打完字符串后删除效果。
## 🧪 TypeScript 支持
组件自带类型定义(`.d.ts`),推荐 `tsconfig.json` 至少包含:
```json
{
"compilerOptions": {
"jsx": "react",
"moduleResolution": "nodenext",
"esModuleInterop": true,
"skipLibCheck": true
}
}
```
## ❓FAQ
**Q: 可以显示 JSX 吗?**\
A: 可以,支持 `strings` 中混合 JSX 元素。元素会一次性显示,不会打字。
**Q: 可以循环播放吗?**\
A: 可以,通过 `loop` 属性控制。
**Q: 可以在打完后自动删除再显示下一条吗?**\
A: 可以,通过 `deleteMode` 属性控制。
## 📜 许可证
[MIT](./LICENSE)