Files
template-10556/docs/RichText使用指南.md
2025-07-08 21:42:38 +08:00

92 lines
1.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Taro RichText 富文本组件使用指南
## 基本用法
```tsx
import { RichText } from '@tarojs/components';
// 显示HTML字符串
<RichText
nodes={htmlString}
space="nbsp"
/>
```
## 主要属性
### nodes
- **类型**: `string | Array<Node>`
- **说明**: 富文本内容支持HTML字符串或节点数组
### space
- **类型**: `'ensp' | 'emsp' | 'nbsp'`
- **说明**: 显示连续空格的方式
- `ensp`: 中文字符空格一半大小
- `emsp`: 中文字符空格大小
- `nbsp`: 根据字体设置的空格大小
### selectable
- **类型**: `boolean`
- **默认值**: `false`
- **说明**: 富文本是否可以长按选中
## HTML内容处理
### 支持的HTML标签
- 文本标签: `p`, `span`, `div`, `h1-h6`, `strong`, `b`, `em`, `i`
- 列表标签: `ul`, `ol`, `li`
- 其他标签: `img`, `a`, `br`, `hr`
### 样式处理
富文本内容的样式通过CSS全局样式定义
```scss
.content {
:global {
p { margin: 16px 0; }
img { max-width: 100%; }
// 更多样式...
}
}
```
## 实际应用示例
### 文章详情页面
```tsx
<View className={'content text-gray-700 text-sm'}>
<RichText
nodes={item?.content || ''}
space="nbsp"
/>
</View>
```
### 协议页面
```tsx
<View className={'content text-gray-700 text-sm p-4'}>
<RichText nodes={content}/>
</View>
```
## 注意事项
1. **安全性**: RichText会直接渲染HTML注意防范XSS攻击
2. **性能**: 大量富文本内容可能影响性能
3. **兼容性**: 不同平台对HTML标签支持程度不同
4. **样式**: 使用`:global`确保样式能正确应用到富文本内容
## 常见问题
### 图片不显示
- 检查图片URL是否正确
- 确保图片域名在小程序白名单中
### 样式不生效
- 使用`:global`包裹富文本样式
- 检查CSS选择器优先级
### 内容被截断
- 检查容器高度设置
- 使用`max-width: 100%`防止内容溢出