React Native:如何确定设备是iPhone还是iPad

Ste*_*rey 20 react-native

我知道React Native我们有能力确定iOS或Android是否正在使用该Platform模块运行,但我们如何确定在iOS上使用的设备?

小智 25

截至9.02.2018,也有

import { Platform } from 'react-native'
Platform.isPad // boolean
Run Code Online (Sandbox Code Playgroud)

请注意(截至目前)它没有安卓对应物.

  • 对于本机0.57,未定义 (3认同)

Dan*_*ash 18

最简单的方法是使用宽高比.代码将是:

import { Dimensions } from 'react-native';
const {height, width} = Dimensions.get('window'); 
const aspectRatio = height/width;

if(aspectRatio>1.6) {

   // Code for Iphone

}
else {

   // Code for Ipad

}
Run Code Online (Sandbox Code Playgroud)

iPad的宽高比为4:3(1.334),iPhone的宽高比为16:9(1.778)

Platform.OS === 'ios'在应用上述逻辑之前,请务必使用方法检查您是否在iOS设备上.

  • 请考虑横向肖像位置!上面的代码将你的 iPhone 旋转 90 度时变成 iPad 的样子:-)。 (2认同)

Sud*_*Plz 9

如果您正在寻找一种方法,而不包括第三方库(如react-native-device-info),您还可以:

import { NativeModules } from 'react-native';
const { PlatformConstants } = NativeModules;
const deviceType = PlatformConstants.interfaceIdiom;
Run Code Online (Sandbox Code Playgroud)

deviceType可以取值:phone,pad,tv,carplayunknown.


Max*_*lll 7

您可以粗略地确定正在使用的iOS设备而没有任何外部依赖性...首先查询Platform.OS然后Dimensions模块允许您查询设备的屏幕尺寸,可以转换为设备:http://iosres.com/


Anh*_*vit 6

我使用 isTablet() 来检测 ipad 和 iphone https://github.com/rebeccahughes/react-native-device-info

import { isTablet } from 'react-native-device-info';
if (isTablet()) {
// try something
}
Run Code Online (Sandbox Code Playgroud)


Bri*_*ean 5

您应该能够从模块中获取该信息 react-native-device-info

https://github.com/rebeccahughes/react-native-device-info


dua*_*uan 5

react-native中有一个类型称为PlatformIOSStatic,如果使用打字稿PlatformPlatformIOSStatic则需要强制转换为。

import { Platform, PlatformIOSStatic } from 'react-native'

if (Platform.OS === 'ios') {
  const platformIOS = Platform as PlatformIOSStatic
  console.log(platformIOS.isPad)
  console.log(platformIOS.isTVOS)
}
Run Code Online (Sandbox Code Playgroud)

这里的界面设计非常糟糕,希望RN团队可以对其进行改进。