android - 如何在 Android 中正确使用 React Native 中的仅限 iOS 的组件而不会出错

标签 android react-native

我是 React Native 的新手,正在测试 PushNotificationIOS。但是 checkpermission 调用在 Android 上给我错误。

ExceptionsManager.js:61 Cannot read property 'checkPermissions' of undefined

我猜这是因为我只需要在 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)

最佳答案

我的建议是将特定于平台的代码拆分到单独的文件中。

React Native will detect when a file has a .ios. or .android. extension and load the relevant platform file when required from other components.

MyFile.ios.js
MyFile.android.js

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

const MyFile= require('./MyFile');

然后像这样使用它

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

并且它将运行特定于平台的代码。

另一种方式是

平台模块

React Native provides a module that detects the platform in which the app is running. You can use the detection logic to implement platform-specific code. Use this option when only small parts of a component are platform-specific.

if(Platform.OS === 'ios')

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

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

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

关于android - 如何在 Android 中正确使用 React Native 中的仅限 iOS 的组件而不会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38507534/

相关文章:

java - Android 可分块对象在 Activity 之间克隆

ios - 模拟器显示有关 App Transport Security 策略的错误需要使用安全连接

android - 将utf-8编码转换为android中的字符串

javascript - 仅在 TextInput 焦点/模糊上运行 Reanimated 动画

reactjs - 如何在移动到下一个屏幕之前等待 React useEffect Hook 完成

xamarin - 是否可以在构建的应用程序中查看 React Native 源代码?

android - React Native ScrollView 与成长中的 child

android - 使用 ACTION_SEND 在 Android 中发布到 Facebook

android - Android 上的 kSOAP2 和 SOAPAction

java - 基于字符串加载图片