我知道React Native我们有能力确定iOS或Android是否正在使用该Platform模块运行,但我们如何确定在iOS上使用的设备?
小智 25
截至9.02.2018,也有
import { Platform } from 'react-native'
Platform.isPad // boolean
Run Code Online (Sandbox Code Playgroud)
请注意(截至目前)它没有安卓对应物.
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设备上.
如果您正在寻找一种方法,而不包括第三方库(如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,carplay和unknown.
我使用 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)
react-native中有一个类型称为PlatformIOSStatic,如果使用打字稿Platform,PlatformIOSStatic则需要强制转换为。
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团队可以对其进行改进。
| 归档时间: |
|
| 查看次数: |
21150 次 |
| 最近记录: |