javascript - 使用本地 javascript 反应 Native WebView
问题描述
我将使用 WebView 创建一个 React Native 应用程序。此视图必须包含本地 HTML 和 Javascript 文件。这是代码。
---> WVView.js
...
render(){
return (
<View style={{flex:1}}>
<StatusBar/>
<WebView
nativeConfig={{props: {webContentsDebuggingEnabled: true}}}
ref={webview => { this.myWebView = webview; }}
source={require('./Resources/index.html')}
javaScriptEnabled={true}
injectedJavaScript={}
onMessage={this.onWebViewMessage}
style={{flexBasis: 1, flexGrow:1}}
scrollEnabled={false}
/>
</View>
);
}
...
---> index.html
<div class="widget-container">
<div id="test12"></div>
<script type="text/javascript" src="./Utils.js"></script>
<script type="text/javascript" src="./WebViewBrdge.js"></script>
<script type="text/javascript" src="./TVS.js"></script>
</div>
---> 目录
|__ WVView.js
|__ Resources
|__ index.html
|__ Utils.js
|__ WebViewBridge.js
|__ TVS.js
请问,您能建议开发此解决方案的最佳方法吗?当我阅读文档时,我发现诸如 source{{html:...}} 或注入的Javascript 之类的代码用于加载静态本地 javascript。我找不到类似的例子。
现在我无法加载 javascript 文件。谢谢
解决方案
首先,在 android 的情况下将文件(资源文件夹本身)添加到 android 资产目录中,在 ios 的情况下在 XCode 项目中添加。
android
:“YourApp/android/app/src/main/assets”
ios
:“YourApp/ios”
然后在变量中获取该文件夹的路径并将其设置为 baseUrl。
android
:“文件:///android_asset/资源”
ios
:“资源/”
您可以使用本机文件路径来加载 html 文件
htmlPath = "file:///android_asset/Resources/index.html"; //file path from native directory;
<WebView
source={{ uri: htmlPath, baseUrl: baseUrl }}
/>
在此之后,您的脚本将被加载到 webview 中。
这是供您参考的链接:https ://github.com/react-native-community/react-native-webview/blob/master/docs/Guide.md#loading-local-html-files
推荐阅读
- sql - 调用任何存储过程时预执行查询
- python - 如何在创建多个新列的 pandas.core.groupby.GroupBy 函数上运行单个聚合函数
- sql - VBA访问中的while循环
- c++ - 将数据返回自动到新的双精度
- excel - 从属下拉框(表单控件) Excel
- angular - 如何使用 Angular 2+ 在本地下载 PDF?
- azure-cosmosdb - 我们应该称之为 DocumentDb 还是 CosmosDB SQL Api
- angular - 更改 ng-multiselect-dropdown 的 css
- matlab - MATLAB 索引后从 double 到 int32 的不需要的转换
- c# - 使用确切的 XPATH(n) 将 XML 属性转换为字符串/列表