如何解决React Native 上的屏幕方向
我正在尝试使用 expo 在 react native 上添加旋转功能。遵循教程并在谷歌和这里搜索,但不知何故他们都没有工作。旋转模拟器时未检测到屏幕尺寸。因此它不会从纵向变为横向,反之亦然。 您可以在下面看到我按照一个工作示例尝试的代码,但是当我应用它时它不起作用。非常感谢任何帮助。
const [orientation,setOrientation] = useState("");
const window = useWindowDimensions();
useEffect(() => {
Dimensions.addEventListener("change",({ window: { width,height } }) => {
if (width < height) {
// this is in portrait mode
setOrientation("Portrait");
} else {
// this is in landscape mode
setOrientation("Landscape");
}
});
},[]);
return (
<View style={styles.container}>
<Text style={{ color: "red",fontSize: 30,fontWeight: "bold" }}>
{orientation}
</Text>
</View>
const styles = StyleSheet.create({
container: {
flex: 1,alignItems: "center",justifyContent: "center",},});
解决方法
我有一个非常干净有效的方法来解决这个问题
创建一个名为 components
的文件夹,并在其中创建一个名为 Orientation.js
的文件
然后在Orientation.js
内
import { Dimensions } from 'react-native';
const msp = (dim,limit) => {
return dim.scale * dim.width >= limit || dim.scale * dim.height >= limit;
};
const isPortrait = () => {
const dim = Dimensions.get('screen');
return dim.height >= dim.width;
};
const isLandscape = () => {
const dim = Dimensions.get('screen');
return dim.width >= dim.height;
};
const isTablet = () => {
const dim = Dimensions.get('screen');
return (
(dim.scale < 2 && msp(dim,1000)) || (dim.scale >= 2 && msp(dim,1900))
);
};
const isPhone = () => {
return !isTablet();
};
export default {
isPortrait,isLandscape,isTablet,isPhone,};
然后像这样设置您的 state
和 useEffect
import Orientation from "./components/Orientation"
const [orientation,setOrientation] = useState(
Orientation.isPortrait() ? 'portrait' : 'landscape'
);
useEffect(() => {
Dimensions.addEventListener('change',() => {
setOrientation(Orientation.isPortrait() ? 'portrait' : 'landscape');
});
},[]);
这将根据您的需要完美运行
结果:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。