【问题标题】:React Native: WebView load static local fileReact Native:WebView 加载静态本地文件
【发布时间】:2017-01-28 04:35:24
【问题描述】:

我目前正在使用 WebView 通过require 加载静态页面。但是该 html 文件中包含一些图像、css、js 文件。它仍然可以在 Android、ios 调试器上运行,但不能在真实设备上运行。

如何捆绑已发布应用的所有资源文件以及它们将位于什么路径?我想要像{uri: 'file://.../index.html'}这样的路径

我不想将文件上传到在线服务器,它只是一个静态页面,我希望我的应用程序可以在不连接互联网的情况下运行。

【问题讨论】:

    标签: android ios reactjs react-native


    【解决方案1】:

    好吧...我终于有了ios,很难获得文件index.html的URI路径。但我找到了替代解决方案。

    对于 Android,只需将文件复制到 android/app/src/main/assets。示例:

    文件android/app/src/main/assets/web/index.html 将有 URI 路径为file:///android_asset/web/index.html

    对于 ios,它不像 Android 那样容易。我使用了名为react-native-fs的第三方库。

    1. 我们需要使用 Xcode 将静态文件/文件夹复制到 ios 项目。
    2. 使用 react-native-fs 列出主包中的所有文件/文件夹并过滤它们:Example Code

    这是我的 ios 代码,用于获取web/index.html 的 URI 路径:

    if (Platform.OS === 'ios') {
            const results = await RNFS.readDir(RNFS.MainBundlePath);
            const webFolder = results.filter(f => f.name == 'web');
            this.setState({fireworkURI: 'file://' + webFolder[0].path + '/index.html'})
        }
    

    另一种方法是将静态文件夹作为http服务器,这种方法更容易编程,但我不喜欢它,因为性能低。对于任何对此方法感兴趣的人,请查看react-native-httpserver

    【讨论】:

    • 此解决方案不适用于 Android 上的 React Native 0.44。
    • @Rai 你可以试试 react-native-fs 替代
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 2021-05-28
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多