【问题标题】:How can I get the device name from UIDevice with React Native?如何使用 React Native 从 UIDevice 获取设备名称?
【发布时间】:2015-08-11 04:43:38
【问题描述】:

我想通过 React Native 访问设备名称(来自 UIDevice)。有什么好办法吗?

【问题讨论】:

  • 我知道它可以从 UIDevice 访问,我想知道是否有 React Native 库或暴露 UIDevice 的方法。
  • NSLog(@"uniqueIdentifier: %@", [[UIDevice currentDevice] uniqueIdentifier]); NSLog(@"name: %@", [[UIDevice currentDevice] name]); NSLog(@"systemName: %@", [[UIDevice currentDevice] systemName]); NSLog(@"systemVersion: %@", [[UIDevice currentDevice] systemVersion]); NSLog(@"model: %@", [[UIDevice currentDevice] model]); NSLog(@"localizedModel: %@", [[UIDevice currentDevice]localizedModel]);
  • 您的评论没有帮助,因为它忽略了问题的 React Native 部分。
  • 这是一个提供设备信息的组件,您可以扩展它github.com/GertjanReynaert/react-native-device 或构建您自己的一个原生组件

标签: ios react-native


【解决方案1】:

您需要创建一个Native Modules (iOS)。步骤如下:

  • 制作用于获取设备名称的原生 iOS 组件
  • 在JS中使用

1.制作组件

//  Device.h
@import UIKit;
#import "RCTBridgeModule.h"

@interface Device : NSObject <RCTBridgeModule>

@end

//  Device.m
#import "Device.h"

@implementation Device
RCT_EXPORT_MODULE()

RCT_EXPORT_METHOD(deviceName:(RCTResponseSenderBlock)callback) {
  NSString *deviceName = [[UIDevice currentDevice] name];
  callback(@[deviceName]);
}
@end

2.在JS中使用

var Device = require('react-native').NativeModules.Device;
Device.deviceName( (name) => {
  console.log(name) 
});

【讨论】:

  • 设备在 JS 中未定义,我收到此错误:Cannot read property 'deviceName' of undefined
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-04
  • 2013-10-06
  • 2020-03-03
  • 1970-01-01
相关资源
最近更新 更多