react-native-orientation 橫屏實(shí)現(xiàn)

https://github.com/yamill/react-native-orientation
github地址

我簡(jiǎn)易的羅列幾個(gè)步驟
1.npm install react-native-orientation --save
2.react-native link react-native-orientation

簡(jiǎn)單使用
引入
import Orientation from 'react-native-orientation';

1.在進(jìn)去這個(gè)頁(yè)面的時(shí)候強(qiáng)制橫屏

componentWillMount() {
       Orientation.lockToLandscape();
}

2.在退出當(dāng)前頁(yè)面的時(shí)候強(qiáng)制豎屏

componentWillUnmount() {
       Orientation.lockToPortrait();
}

這樣就可以滿足某一頁(yè)面橫屏的需求,下面的是系統(tǒng)的寫法,還能控制轉(zhuǎn)換

export default class AppScreen extends Component {
  // ...

  componentWillMount() {
    // The getOrientation method is async. It happens sometimes that
    // you need the orientation at the moment the JS runtime starts running on device.
    // `getInitialOrientation` returns directly because its a constant set at the
    // beginning of the JS runtime.

     // 判斷橫豎屏幕
    const initial = Orientation.getInitialOrientation();
    if (initial === 'PORTRAIT') {
      // do something
    } else {
      // do something else
    }
  },

  componentDidMount() {
    // this locks the view to Portrait Mode
    Orientation.lockToPortrait();

    // this locks the view to Landscape Mode
    // Orientation.lockToLandscape();

    // this unlocks any previous locks to all Orientations
    // Orientation.unlockAllOrientations();

    Orientation.addOrientationListener(this._orientationDidChange);
  },

  _orientationDidChange = (orientation) => {
    if (orientation === 'LANDSCAPE') {
      // do something with landscape layout
    } else {
      // do something with portrait layout
    }
  },

  componentWillUnmount() {
    Orientation.getOrientation((err, orientation) => {
      console.log(`Current Device Orientation: ${orientation}`);
    });


    // Remember to remove listener
    Orientation.removeOrientationListener(this._orientationDidChange);
  }

  render() {
    // ...

    return (
      // ...
    )
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容