https://github.com/yamill/react-native-orientation
github地址
我简易的罗列几个步骤
1.npm install react-native-orientation --save
2.react-native link react-native-orientation
简单使用
引入
import Orientation from 'react-native-orientation';
1.在进去这个页面的时候强制横屏
componentWillMount() {
Orientation.lockToLandscape();
}
2.在退出当前页面的时候强制竖屏
componentWillUnmount() {
Orientation.lockToPortrait();
}
这样就可以满足某一页面横屏的需求,下面的是系统的写法,还能控制转换
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 (
// ...
)
}
}