1、安装
- 官方链接:https://www.npmjs.com/package/react-native-orientation
#安装
npm install react-native-orientation --save
#链接所有依赖
react-native link react-native-orientation
2、官方API
#锁定为竖屏
lockToPortrait()
#锁定为横屏
lockToLandscape()
#锁定为左竖屏
lockToLandscapeLeft()
#锁定为右竖屏
lockToLandscapeRight()
#解除所有锁定
unlockAllOrientations()
#得到当前屏幕的信息
getOrientation((err, orientation) => {})
getSpecificOrientation((err, specificOrientation) => {})
3、添加、移除监听
Orientation.addOrientationListener((orientation)=>{});
Orientation.addSpecificOrientationListener((specificOrientation)=>{});
removeOrientationListener((orientation)=> {});
removeSpecificOrientationListener((specificOrientation)=> {});
4、代码示例
import React, {Component} from 'react';
import {Button, StyleSheet, Text, View} from 'react-native';
import Orientation from 'react-native-orientation';
export default class App extends Component<Props> {
constructor() {
super(...arguments);
this.state = {
isBool: Orientation.getInitialOrientation() === 'PORTRAIT',
summary: ''
};
this._handleOnPress = this._handleOnPress.bind(this);
}
componentDidMount() {
Orientation.lockToPortrait();
}
_handleOnPress = () => {
const {isBool} = this.state;
if (isBool) {
this.setState({isBool: false, summary: '本来是竖屏、现在锁定为横屏了....'});
Orientation.lockToLandscape();
} else {
this.setState({isBool: true, summary: '本来是横屏、现在锁定为竖屏了....'});
Orientation.lockToPortrait();
}
};
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>方向:{this.state.isBool ? '竖屏' : '横屏'}</Text>
<Text style={styles.welcome}>描述:{this.state.summary}</Text>
<Button title={'切换屏幕方向'}
onPress={() => this._handleOnPress()}/>
</View>
);
}
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
}
});
5、效果展示
1):默认
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/484d94b35b3b1932e2d4d8717362db9a.png)
2):竖屏切换为横屏
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3a14c47b31939e25abb2a7089475d2ce.png)
3):横屏切换为竖屏
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7d3e5aa57158f6e523315f66334e35a7.png)
6、 解决打包编译异常问题,Execution failed for task ‘:react-native-orientation:verifyReleaseResources’.
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c36f087e4b6e37296e332bfc17bd0a6b.png)
1):修改node_modules\react-native-orientation\android\build.gradle文件中、dependencies下compile为implementation。
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/bcf67df5866913ae157945cb0803831d.png)
2):修改node_modules\react-native-orientation\android\build.gradle文件、与android\build.gradle文件版本保持一致。
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/26ae6a9892e32311bf9f6fcbe5cd7cff.png)
3):重新打包即可。
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ed5ec4317e43b14e5ca7474573877077.png)
4):RN打包离线APK参考链接:https://blog.csdn.net/weixin_44187730/article/details/86492907