首页 > 解决方案 > 使用本地 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 文件。谢谢

标签: javascripthtmlreact-nativewebviewreact-native-webview

解决方案


首先,在 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


推荐阅读