如何在Android中正确使用React Native中仅有iOS的组件而不会出现错误

Reb*_*ong 4 android react-native react-native-android

我是React Native的新手并测试了PushNotificationIOS.但是checkpermission调用在Android上给我错误.

ExceptionsManager.js:61 Cannot read property 'checkPermissions' of undefined
Run Code Online (Sandbox Code Playgroud)

我猜这是因为我只需要在iOS上使用该组件.如何添加操作系统检查才能在iOS上拨打电话?

这是我的代码:

  componentWillMount: function() {
    //--  need an OS check here??
    PushNotificationIOS.checkPermissions((data)=> {
      console.log("in comp will mount: checking for permission")
      console.log(data.alert)
      console.log(data.badge)
Run Code Online (Sandbox Code Playgroud)

Tra*_*ain 5

我建议将该平台特定代码拆分为单独的文件.

React Native将检测文件何时具有.ios.或.android.在需要时从其他组件扩展并加载相关平台文件.

MyFile.ios.js
MyFile.android.js
Run Code Online (Sandbox Code Playgroud)

然后,您可以按如下方式要求组件:

const MyFile= require('./MyFile');
Run Code Online (Sandbox Code Playgroud)

并像这样使用它

componentWillMount: function() {
    //--  it would call the logic of what ever platform was detected automatically
    MyFile.CallWhatEver();
Run Code Online (Sandbox Code Playgroud)

它将运行特定于平台的代码.

另一种方式是

平台模块

React Native提供了一个模块,用于检测运行应用程序的平台.您可以使用检测逻辑来实现特定于平台的代码.当只有组件的小部分是特定于平台时,请使用此选项.

if(Platform.OS === 'ios')
Run Code Online (Sandbox Code Playgroud)

还有一个platform.select可以接受任何价值的东西

const Component = Platform.select({
  ios: () => //function goes here,
  android: () => require('ComponentAndroid'),
})();
Run Code Online (Sandbox Code Playgroud)

链接 https://facebook.github.io/react-native/docs/platform-specific-code.html