简体   繁体   English

我如何知道我的代码是否作为 React Native 运行

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

I want to be able to export a package for all platforms, but I am using some native bindings with a plain JS fallback.我希望能够为所有平台导出 package,但我正在使用一些带有普通 JS 后备的本机绑定。 Normally I would notice the difference checking if object window or exports exist.通常我会注意到检查 object windowexports是否存在的差异。

How can I achieve this on React Native?如何在 React Native 上实现这一点?

Here is how to check if code is on web, nodejs, or react-native: 以下是检查代码是否在web,nodejs或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: 资料来源:

crete两个文件:一个名为file.web.js,另一个名为file.native.js,只导入第一个名称段'./ yourdirectories / file'

Use利用

import { Platform } from 'react-native'

if ( Platform.OS !== 'web' ) {
    // Do something
}

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: 不确定我是否理解你的问题,但到目前为止我们一直在做的事情是解决所有平台并且让React Native重写是:

-- 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. 因此,基于env(Node / React Native),可以透明地加载正确的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM