React Native开发鸿蒙Next---富文本浏览

React Native开发鸿蒙Next---富文本浏览

最近在继续开发App剩余的社区功能。地铁的社区相对较为特殊,只有公告/政策规章/操作指南等资讯阅读功能,无法进行交互。对于原先的社区RN,除了移植适配鸿蒙,还需要做大量的功能屏蔽等改造。新的社区后台大量采用富文本进行内容编辑,这里介绍一个非常方便的鸿蒙RN三方组件:

@react-native-oh-tpl/react-native-autoheight-webview

react-native-autoheight-webview是一个可以自适应内容高度的web组件,组件在ArkTS原生端需要基于
@react-native-oh-tpl/react-native-webview实现。在引入组件之前需要首先完成@react-native-oh-tpl/react-native-webview的导入,过程可以参考以下文档:

https://gitee.com/react-native-oh-library/usage-docs/blob/master/zh-cn/react-native-webview.md

其中需要注意的是完成webview组件在原生端的代码导入并能正常引用到。

cpp/generated


image.png

PackageProvider.cpp


image.png

CMakeList.txt


image.png

image.png

RNPackagesFactory.ets


image.png

完成webview的导入后react-native-autoheight-webview只需要在rn侧添加依赖。autoheight-webview是远程包。

"@react-native-oh-tpl/react-native-autoheight-webview": "^1.6.5-0.0.6",

rn代码中使用较为简单,向组件添加富文本或者html内容即可。会根据内容高度撑开web组件。

import AutoHeightWebView from '@react-native-oh-tpl/react-native-autoheight-webview';
......
return (
  <View>
  {richContent && (  
  <AutoHeightWebView    
      source={{html: richContent}}  
  />
  </View>
)

可以通过customStyle,injectedJavaScript分别向web添加自定义css与注入js,来对富文本内容做进一步控制,如添加栅格。

{richContent && (
          <AutoHeightWebView
            source={{html: richContent}}
            customStyle={`
    * {
      max-width: 100% !important;
      font-size: 16px !important;
      line-height: 1.5 !important;
    }
    img {
      width: 100% !important;
      height: auto !important;
    }
    table {
      width: 100% !important;
      overflow-x: auto !important;
    }
    div {
      overflow-x: auto !important;
      word-wrap: break-word !important;
    }
  `}
    injectedJavaScript={`
    const meta = document.createElement('meta');
    meta.setAttribute('name', 'viewport');
    meta.setAttribute('content', 'width=device-width-10, initial-scale=1.0');
    document.head.appendChild(meta);
    document.documentElement.style.width = '100%';
  `}
            javaScriptEnabled={true}
            domStorageEnabled={true}
            onSizeUpdated={size => console.log('Updated height:', size.height)}
          />

前端控制需要根据后台传入的实际内容显示情况进行调整。项目中后台用到的富文本编辑器较古老,对移动端的适配较差。最好还是在后台能够处理适配移动端。

整体效果如下(西瓜和抖音合并了似乎无法添加视频了)。
https://www.douyin.com/user/self?from_tab_name=main&modal_id=7480891057203399962&showTab=post


不经常在线,有问题可在微信公众号或者掘金社区私信留言(和我简书账号同名)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容