【REACT NATIVE 系列教程之七】統一Android與iOS兩個平臺的程序入口&&區分平臺的組件簡介

mitk7479 8年前發布 | 23K 次閱讀 Android IOS ReactNative 移動開發 React Native

本篇介紹兩個細節:

1. 關于如何將index.android.js 與index.ios.js統一管理起來。

2.  Platform 組件的簡單介紹與使用 

一:將index.android.js 與index.ios.js統一管理起來。

由于React本身就是跨平臺的,但是創建的React項目總會有各自不同的程序入口文件,如下圖展示目錄結構:

標識1:這里是兩個平臺的項目文件夾,這里一般就是針對各平臺不同配置、嵌入第三方插件等專屬平臺相關設置與添加的地方。

標識2:  React 在不同平臺調用的不同入口文件。

那么正常情況下,我們只要不涉及到某個平臺獨有的特性代碼、組件或插件等,我們就完全沒有必要走兩個不同的入口。否則在Android上運行可能index.ios下運行的代碼段還要拷貝到index.android里,反之亦然。

因此我們可以新建一個組件class 讓倆平臺共同顯示這個class,就可以避免這種來回拷貝浪費的時間。

1. 假設我們新建了一個叫Main.js的組件Class

2. 然后index.ios.js如下:

importReact, {
  AppRegistry,
  Component,
  View,
} from 'react-native';
 
importMainfrom './Main';
 
class AwesomeProject extends Component {
 
    render() {
  return (<Main/>);
  }
}
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);

3.index.android.js如下:

importReact, {
  AppRegistry,
  Component,
  View,
} from 'react-native';
 
importMainfrom './Main';
 
class AwesomeProject extends Component {
 
  render() {
 return (<Main/>);
 }
}
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);

這樣統一顯示Main組件的內容,以后不論在android還是ios平臺都可以完美兼容,小細節,估計大家一看就懂。

二. Platform 組件的簡單介紹與使用 

有時候我們會區分平臺做一些處理,比如充值、適配問題、接入第三方SDK或與原生平臺組件進行交互等等。

這時我們就需要 RN提供的 Platform 組件~ 使用很簡單,就不多贅述了。

示例:

代碼段1:(導入Platform組件)

importReact, { 
  ...
  Platform,
  ...
} from 'react-native';

代碼段2:

estAlert(){
    if(Platform.OS === 'ios'){
      Alert.alert('測試當前平臺', 'iOS平臺');
    }else if(Platform.OS === 'android'){
      Alert.alert('測試當前平臺', 'Android平臺');
    }
  }
 
  render() {
    return (
  <Viewstyle={styles.himiViewStyle} >
  <Text style={styles.himiTextStyle}>HimiReactNative 教程</Text>
 
        <Viewstyle={styles.himiViewStyle}>
          <TouchableHighlight
            underlayColor='#f00'
            onPress={this.testAlert.bind(this)}
            >
            <Text style={{fontSize:20}}>點擊查看當前平臺</Text>
          </TouchableHighlight>
        </View>
      </View>
    )
  }

主要看 testAlert 的函數中的內容,通過Platform.OS獲取當前平臺類型與android/ios做比較即可得知。

運行效果如下(點擊查看動態圖):

 

來自: http://www.himigame.com/react-native/2260.html

 

 本文由用戶 mitk7479 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!