写点什么

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

作者:悬空八只脚
  • 2025-03-25
    江苏
  • 本文字数:1424 字

    阅读完需:约 5 分钟

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



PackageProvider.cpp



CMakeList.txt



RNPackagesFactory.ets



完成 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




不经常在线,有问题可在微信公众号或者掘金社区私信留言

更多内容可关注

我的公众号悬空八只脚

作者:悬空八只脚链接:https://juejin.cn/post/7480732440287445033

来源:稀土掘金

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

发布于: 刚刚阅读数: 4
用户头像

还未添加个人签名 2021-05-29 加入

还未添加个人简介

评论

发布
暂无评论
React Native开发鸿蒙Next---富文本浏览_React Native_悬空八只脚_InfoQ写作社区