用框架react-native-orientation可以輕易做到。
- 安裝依賴
npm install --save react-native-orientation
- 自動(dòng)鏈接庫(kù)
react-native link react-native-orientation
如果自動(dòng)鏈接失敗,則看官方文檔,手動(dòng)鏈接,傳送門。
- 使用方式
引入Orientation后,用這個(gè)組件的Api能做到反轉(zhuǎn)橫屏和豎屏啦。這里列出幾個(gè)常用方法:
Orientation.lockToPortrait() //轉(zhuǎn)成豎屏
Orientation.lockToLandscape() //轉(zhuǎn)成橫屏
Orientation.lockToLandscapeLeft() //轉(zhuǎn)成橫屏(向左)
Orientation.lockToLandscapeRight() //轉(zhuǎn)成橫屏(向右)
一個(gè)簡(jiǎn)單的例子:
import Orientation from 'react-native-orientation'
...//省略其他代碼
<Button
title={this.state.buttonTitle}
onPress={() => {
this.state.buttonTitle === '全屏' ?
Orientation.lockToLandscape() :
Orientation.lockToPortrait();
this.setState({buttonTitle: this.state.buttonTitle === '全屏' ? '退出全屏' : '全屏'})
console.log(this.state.buttonTitle)}} />