react-native渲染富文本的几种方案

前言

在日常开发中,经常需要用到富文本编辑器来编辑业务内容,例如新闻、论坛等,然后在用到的地方进行渲染,一般在web端可以直接在html中载入编辑好的内容(一般是一段html),不过在react-native的app中不能直接把html渲染进去,接下来我介绍几种渲染html的方案。

正文

1、使用已有的组件

既然已经有人造好了轮子,我们就直接拿来用就可以了。可以在网上搜 react-native 富文本组件,可以有几个选择方案,我这边以react-native-render-html,npm地址:www.npmjs.com/package/rea…

使用方法:
import RenderHTML , {IMGElementContainer, useIMGElementProps, useIMGElementState, IMGElement} from "react-native-render-html";

// 其他代码 ...
_previewImg = (src) => {const images = [{ uri : src}];Overlay.show((<Overlay.PopViewcontainerStyle={
  {flex: 1}}overlayOpacity={1}ref={v => this.fullImageView = v}><AlbumViewstyle={
  {flex: 1}}control={true}images={images}defaultIndex={0}onPress={() => {this.fullImageView && this.fullImageView.close()}}/></Overlay.PopView>));
};

_imagesNode = (props) => {const imgElementProps = useIMGElementProps(props);return (<IMGElementonPress={this._previewImg.bind(this, imgElementProps.source.uri)}source={imgElementProps.source}contentWidth={imgElementProps.contentWidth - 15}/>);
};

render() {const styles = this.styles;const Props = this.props;return (<RenderHTMLsource={
  {html: this._handleContent(Props.data)}}renderers={
  {img: this._imagesNode}}tagsStyles={
  {p: {marginVertical: 5}}}{...Props}/>);
}
// 其他代码 ... 

这个组件的原理就是把富文本的html标签一个个的解析出来,转换成react-native的标签,再进行渲染就可以了。

注意:如果需要点击放大预览的话,图片需要单独处理。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值