富文本即RichText,一般是有文字有圖的一種組合。示例如下:
"<p>第一段</p><p align="center"><img src="result.png"></p><p>第二段</p><p>第三段</p>"
這是html串,有p和img標簽。
使用taro開發小程序實現富文本的方法為:
1.引入RichText組件
import { View, Text, Image, RichText } from '@tarojs/components'
2.使用該組件
<View className="content"> <RichText nodes={processRichText(data.article)}></RichText> </View>
3.調用函數對img標簽進行處理。
max-width:100%是對圖片寬度加以限制,避免超出屏幕。
height:auto為高度自適應。
display:block可以去掉圖片之間的空白間隔。
export let processRichText = (str)=>{ if(str){ return str.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block"') }else{ return '' } }
