本篇介紹兩個細節:html
1. 關於如何將index.android.js 與index.ios.js統一管理起來。react
2. Platform 組件的簡單介紹與使用 android
一:將index.android.js 與index.ios.js統一管理起來。ios
因爲React自己就是跨平臺的,可是建立的React項目總會有各自不一樣的程序入口文件,以下圖展現目錄結構:react-native
標識1:這裏是兩個平臺的項目文件夾,這裏通常就是針對各平臺不一樣配置、嵌入第三方插件等專屬平臺相關設置與添加的地方。ide
標識2: React 在不一樣平臺調用的不一樣入口文件。函數
那麼正常狀況下,咱們只要不涉及到某個平臺獨有的特性代碼、組件或插件等,咱們就徹底沒有必要走兩個不一樣的入口。不然在Android上運行可能index.ios下運行的代碼段還要拷貝到index.android裏,反之亦然。測試
所以咱們能夠新建一個組件class 讓倆平臺共同顯示這個class,就能夠避免這種來回拷貝浪費的時間。this
1. 假設咱們新建了一個叫Main.js的組件Classurl
2. 而後index.ios.js以下:
import React, { AppRegistry, Component, View, } from 'react-native'; import Main from './Main'; class AwesomeProject extends Component { render() { return (<Main/>); } } AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
3.index.android.js以下:
import React, { AppRegistry, Component, View, } from 'react-native'; import Main from './Main'; class AwesomeProject extends Component { render() { return (<Main/>); } } AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
這樣統一顯示Main組件的內容,之後不論在android仍是ios平臺均可以完美兼容,小細節,估計你們一看就懂。
二. Platform 組件的簡單介紹與使用
有時候咱們會區分平臺作一些處理,好比充值、適配問題、接入第三方SDK或與原平生臺組件進行交互等等。
這時咱們就須要 RN提供的 Platform 組件~ 使用很簡單,就很少贅述了。
示例:
代碼段1:(導入Platform組件)
import React, { ... Platform, ... }
代碼段2:
testAlert(){ if(Platform.OS === 'ios'){ Alert.alert('測試當前平臺', 'iOS平臺'); }else if(Platform.OS === 'android'){ Alert.alert('測試當前平臺', 'Android平臺'); } } render() { return ( <View style={styles.himiViewStyle} > <Text style={styles.himiTextStyle}>Himi React Native 教程</Text> <View style={styles.himiViewStyle}> <TouchableHighlight underlayColor='#f00' onPress={this.testAlert.bind(this)} > <Text style={{fontSize:20}}>點擊查看當前平臺</Text> </TouchableHighlight> </View> </View> ) }
主要看 testAlert 的函數中的內容,經過Platform.OS獲取當前平臺類型與android/ios作比較便可得知。
運行效果以下(點擊查看動態圖):