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 && (<AutoHeightWebViewsource={{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
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。