we-rich 小程序渲染富文本js库

最近项目需要, 把公众号的文章直接在小程序显示, 页面除了文章内容以外,还有其他组件.

小程序中渲染html, 解决方案有三个

  1. 使用wxParse把html转化成小程序标签
  2. 使用web-view组件
  3. 使用rich-text组件

第一个方案是由于小程序还没有更新2,3的功能时的一个临时解决办法. 而使用web-view控件最大问题只能整屏显示.

于是翻阅rich-text控件的文档说明.也是坑满满的.

rich-text的控件使用很简单, 只需要给nodes属性赋值要渲染的html节点数组或者直接是html代码即可.

一开始想偷懒, 直接在nodes重赋值html代码. 发现基本无法使用. 因为rich-text不支持的标签很多, 遇到不支持的标签(比如section)会忽略解析.导致很多的html内容都会莫名消失.

只能乖乖的把html代码变成节点数组,然后对每个节点进行判断兼容.

于是有了we-rich这个库.

we-rich 直接把html代码转化成小程序rich-text 可以渲染的nodes节点

    <div class='post post-featured'>
      <p>hello</p>
      <section>world</section>
      <img src="test.png" style="max-width:100%" />
    </div>
复制代码
[ 
  {
    "type": "node",
    "name": "div",
    "attrs": {"class": "post post-featured"},
    "children": [ 
      {
        "type": "node",
        "name": "p",
        "attrs": {},
        "children": [{"type": "text", "text": "hello"} ]
      }, 
      {
        "type": "node",
        "name": "div",
        "attrs": {},
        "children": [{"type": "text", "text": "world"}
        ]
      }, 
      {
        "type": "node",
        "name": "img",
        "attrs": {"src": "test.png", "style": "max-width:100%"},
        "children": []
      }
    ]
  }
] 
复制代码

使用办法

npm install we-rich

var weRich = require('we-rich');
var nodes = weRich.parse(html)
复制代码

转载于:https://juejin.im/post/5a4745b851882538650984c9

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值