React Native WebView使用本地JavaScript

4

我将创建一个带有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:...}}或injectedJavascript用于加载静态本地javascript的示例。 我没有找到类似的示例。

现在我无法加载javascript文件。 谢谢

1个回答

10

首先,在Android系统下将你的文件(如资源文件夹)添加到assets目录中,在iOS系统下添加到XCode项目中。
Android: "YourApp/android/app/src/main/assets"
iOS: "YourApp/ios"

然后将该文件夹的路径放入一个变量中,并将其设置为baseUrl。
Android: "file:///android_asset/Resources"
iOS: "Resources/"

你可以使用本地文件路径来加载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


1
谢谢。在Expo项目中有没有一种方法可以执行此过程?我该如何将文件添加到资产目录中?我找到了这个问题的部分解决方案。 - zp26
首先,在问题中提到您正在使用 Expo 项目。上面的解决方案仅在您使用 React Native CLI 创建项目或将 Expo 项目弹出到本机项目时才有用。 - Ankit Makwana
@zp26,答案中有一个错误,我已经纠正了。我还在安卓上测试过了,它运行良好。试一下,如果你遇到任何问题,请告诉我。 - Ankit Makwana
我在iOS上测试了您的解决方案,但无法复制它。 htmlPath是像“Resources/index.html”这样的吗? 在我看来,source属性应该是这样的: source={{ uri: htmlPath, baseUrl: baseUrl }} - zp26
baseUrl在安卓上无法工作,但是file:///android_asset/img-editor/example03-mobile.html对我有效。 - Aman Deep

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接