在react native中使用 “react-native-webview”: “^13.13.5”,加载HTML文件
Android:
将HTML文件放置到android/src/main/assets目录,访问
{uri: 'file:///android_asset/markmap/index.html'}
ios:
在IOS中可以直接可以直接放在react native项目下,访问方式如下
require('../../assets/markmap.html')
这里遇到一个问题是编译出来的HTML文件中带有单独的js和CSS的时候在iOS中无法加载成功,解决方法是用vite-plugin-singlefile将前端项目导出为单独文件,我的vite.config.js配置如下:
import {defineConfig} from 'vite'
import react from '@vitejs/plugin-react'
import {viteSingleFile} from "vite-plugin-singlefile";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react(),viteSingleFile()],
base: './', // 设置为相对路径
})
如果是其他的打包方式也实现同样的功能就行。
完整的代码:
<WebView
ref={webViewRef}
source={Platform.OS==='android'?{uri: 'file:///android_asset/markmap/index.html'}:require('../../assets/markmap.html')}
style={styles.webView}
originWhitelist={['*']}
javaScriptEnabled={true}
domStorageEnabled={true}
allowFileAccess={true}
allowFileAccessFromFileURLs={true}
allowUniversalAccessFromFileURLs={true}
onMessage={handleMessage}/>