How do I know if my code is running as React Native

前端 未结 3 400
余生分开走
余生分开走 2021-01-02 01:10

I want to be able to export a package for all platforms, but I am using some native bindings with a plain JS fallback. Normally I would notice the difference checking if obj

相关标签:
3条回答
  • 2021-01-02 01:26

    Here is how to check if code is on web, nodejs, or react-native:

    if (typeof document != 'undefined') {
      // I'm on the web!
    }
    else if (typeof navigator != 'undefined' && navigator.product == 'ReactNative') {
      // I'm in react-native
    }
    else {
      // I'm in node js
    }
    

    Sources:

    • What causes node to return 'navigator is not defined'
    • Add way to detect react-native (and platform) without require().
    • React Native support is broken
    0 讨论(0)
  • 2021-01-02 01:27

    crete two files: one called file.web.js, and other file.native.js, and import only the first name segment'./yourdirectories/file'

    0 讨论(0)
  • 2021-01-02 01:28

    Not sure if I understood your question properly, but what we've been doing so far to address all the platforms and have React Native overrides was to have:

    -- file.js
    -- file.android.js
    -- file.ios.js
    

    with just a plain

    require('./file');
    

    so that based on the env (Node / React Native) a proper file is loaded transparently.

    0 讨论(0)
提交回复
热议问题