从 url 动态加载本机组件

Ken*_*nne 5 reactjs react-native

是否可以在 React Native 中即时使用加载和缓存远程 React Native 组件?

我们希望能够构建和部署部分 UI 及其各自的后端微服务,以便我们可以集中配置哪些客户端使用哪些组件/后端组合。

Ken*_*nne 0

在 xcode 中打开您的 ios 项目,然后查看 AppDelegate.m。

NSURL *jsCodeLocation;
#ifdef DEBUG
    /**
     * Loading JavaScript code - uncomment the one you want.
     *
     * OPTION 1
     * Load from development server. Start the server from the repository root:
     *
     * $ npm start
     *
     * To run on device, change `localhost` to the IP address of your computer
     * (you can get this by typing `ifconfig` into the terminal and selecting the
     * `inet` value under `en0:`) and make sure your computer and iOS device are
     * on the same Wi-Fi network.
     */
    jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/compiled/src/index.ios.bundle?platform=ios&dev=true"];
  #else
    /**
     * OPTION 2
     * Load from pre-bundled file on disk. The static bundle is automatically
     * generated by the "Bundle React Native code and images" build step when
     * running the project on an actual device or running the project on the
     * simulator in the "Release" build configuration.
     */
    jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
  #endif
Run Code Online (Sandbox Code Playgroud)

如您所见,它已经支持远程和本地加载捆绑包。出于性能原因,绝对不建议在生产中远程加载它。

您可以查看www.apphub.ioCodePush等工具。它们帮助您动态推送更新。

尽管没有一个替代方案可以解决这里提出的问题:如何动态加载单个组件。由于您可以在 JS 中自由地远程加载和评估资源,并且只需要返回使用有效的 React Native 组件的有效 JSX,这绝对不是不可能的!