簡體   English   中英

使用本地 javascript 響應 Native WebView

[英]React Native WebView with local javascript

我將使用 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 文件。 謝謝

首先,在android的情況下在android資產目錄中添加您的文件(Resources文件夾本身),在ios的情況下在XCode項目中添加。
android :“你的應用程序/android/app/src/main/assets”
ios :“你的應用程序/ios”

然后在變量中獲取該文件夾的路徑並將其設置為baseUrl。
android :“文件:///android_asset/Resources”
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM