gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:45:26 26 4
gpt4 key购买 nike

我是 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com