找到 OS TypeVersion

第一步是從’react-native’包中匯入 Platform,如下所示:

import { Platform } from 'react-native'

完成後,你可以繼續通過 Platform.OS 訪問作業系統型別,允許你在條件語句中使用它

const styles = StyleSheet.create({
  height: (Platform.OS === 'ios') ? 200 : 100,
})

如果你想檢測 Android 版本,你可以像這樣使用 Platform.Version

if (Platform.Version === 21) {
  console.log('Running on Lollipop!');
}

對於 iOS,Platform.Version 返回一個 String,對於複雜的條件,不要忘記解析它。

if (parseInt(Platform.Version, 10) >= 9) {
    console.log('Running version higher than 8');
}

如果平臺特定邏輯很複雜,可以基於平臺呈現兩個不同的檔案。例如:

  • MyTask.android.js
  • MyTask.ios.js

並要求使用它

const MyTask = require('./MyTask')