跳到主要內容

平台特定程式碼

當建構跨平台應用程式時,你會希望盡可能重複使用程式碼。在某些情況下,程式碼可能需要有所不同,例如,你可能會想為 Android 和 iOS 實作不同的視覺組件。

React Native 提供了兩種方式來組織你的程式碼,並依平台區隔

某些組件可能具有僅在一個平台上運作的屬性。所有這些屬性都標註了 @platform,並且在網站上它們旁邊會有一個小徽章。

Platform 模組

React Native 提供了一個模組,可以偵測應用程式運行的平台。你可以使用偵測邏輯來實作平台特定的程式碼。當組件中只有小部分是平台特定的時候,請使用此選項。

tsx
import {Platform, StyleSheet} from 'react-native';

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

當在 iOS 上運行時,Platform.OS 將會是 ios,而在 Android 上運行時,則會是 android

還有一個可用的 Platform.select 方法,它接受一個物件,其鍵可以是 'ios' | 'android' | 'native' | 'default' 之一,並返回最適合你目前運行平台的數值。也就是說,如果你在手機上運行,iosandroid 鍵將優先採用。如果沒有指定這些鍵,將會使用 native 鍵,然後是 default 鍵。

tsx
import {Platform, StyleSheet} from 'react-native';

const styles = StyleSheet.create({
container: {
flex: 1,
...Platform.select({
ios: {
backgroundColor: 'red',
},
android: {
backgroundColor: 'green',
},
default: {
// other platforms, web for example
backgroundColor: 'blue',
},
}),
},
});

這將使容器在所有平台上都具有 flex: 1,在 iOS 上具有紅色背景顏色,在 Android 上具有綠色背景顏色,而在其他平台上則具有藍色背景顏色。

由於它接受 any 值,你也可以使用它來返回平台特定的組件,如下所示

tsx
const Component = Platform.select({
ios: () => require('ComponentIOS'),
android: () => require('ComponentAndroid'),
})();

<Component />;
tsx
const Component = Platform.select({
native: () => require('ComponentForNative'),
default: () => require('ComponentForWeb'),
})();

<Component />;

偵測 Android 版本
Android

在 Android 上,Platform 模組也可以用來偵測應用程式運行的 Android 平台版本

tsx
import {Platform} from 'react-native';

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

注意Version 設定為 Android API 版本,而不是 Android OS 版本。若要查找對應關係,請參考 Android 版本歷史記錄

偵測 iOS 版本
iOS

在 iOS 上,Version-[UIDevice systemVersion] 的結果,它是一個包含目前作業系統版本的字串。系統版本的一個範例是 "10.3"。例如,要在 iOS 上偵測主要版本號碼

tsx
import {Platform} from 'react-native';

const majorVersionIOS = parseInt(Platform.Version, 10);
if (majorVersionIOS <= 9) {
console.log('Work around a change in behavior');
}

平台特定的副檔名

當你的平台特定程式碼更複雜時,你應該考慮將程式碼拆分到不同的檔案中。當檔案具有 .ios..android. 副檔名時,React Native 會偵測到,並在其他組件需要時載入相關的平台檔案。

例如,假設你的專案中有以下檔案

shell
BigButton.ios.js
BigButton.android.js

然後你可以如下所示匯入組件

tsx
import BigButton from './BigButton';

React Native 會根據運行的平台自動選取正確的檔案。

原生特定的副檔名(例如,與 NodeJS 和 Web 共用程式碼)

當模組需要在 NodeJS/Web 和 React Native 之間共用,但沒有 Android/iOS 差異時,你也可以使用 .native.js 副檔名。這對於在 React Native 和 ReactJS 之間有共用程式碼的專案特別有用。

例如,假設你的專案中有以下檔案

shell
Container.js # picked up by webpack, Rollup or any other Web bundler
Container.native.js # picked up by the React Native bundler for both Android and iOS (Metro)

你仍然可以不使用 .native 副檔名匯入它,如下所示

tsx
import Container from './Container';

專家提示: 設定你的 Web bundler 忽略 .native.js 副檔名,以避免在你的生產環境 bundle 中包含未使用的程式碼,從而減小最終 bundle 的大小。