1. 程式人生 > >React Native學習-控制橫豎屏第三方元件:react-native-orientation

React Native學習-控制橫豎屏第三方元件:react-native-orientation

在專案中,有時候可能會想使不同的頁面顯示的橫豎屏也不一樣,比如前一段我做的《廣播體操》的專案,在首頁面,肯定是想使頁面為豎屏顯示,但是播放頁面要為橫屏顯示,即使使用者的手機可以轉屏,我們的播放頁面也要是橫屏顯示。

有這樣的需求,我們可以藉助react-native的第三方元件,react-native-orientation。

安裝

1.如果專案正在執行,先關閉模擬器和終端;

2.執行安裝命令:npm install --save react-native-orientation;

3.執行命令:rnpm link

4.現在使用的版本為1.15.0,link執行過之後,我們要需要手動配置

iOS:

1.用Xcode開啟專案,右鍵點選專案名稱,選擇 “Add Files to ‘專案名’ “ ;

2.找到路徑檔案:  專案資料夾/node_modules/react-native-orientation/RCTOrientation  ,將該檔案新增上;

3.然後重新執行專案;

Android:

用法

componentWillMount() {
    // 判斷橫豎螢幕
    var initial = Orientation.getInitialOrientation();
    if (initial === 'PORTRAIT') {
      //do stuff
    } else {
      //do other stuff
    }
    
    // 只允許豎屏
    Orientation.lockToPortrait();
    //只允許橫屏
    Orientation.lockToLandscape();
}

Functions

  • lockToPortrait()
  • lockToLandscape()
  • lockToLandscapeLeft()
  • lockToLandscapeRight()
  • unlockAllOrientations()
  • getOrientation(function(err, orientation)

返回的結果有 LANDSCAPE PORTRAIT UNKNOWN PORTRAITUPSIDEDOWN 

  • getSpecificOrientation(function(err, specificOrientation)

 返回的結果有 LANDSCAPE-LEFT LANDSCAPE-RIGHT

 PORTRAIT UNKNOWN PORTRAITUPSIDEDOWN

官方文件中,還有一些事件的介紹,詳細可以到官方文件上了解學習。