[英]Why when I try to use react native hooks it does not work properly as intended to be?
I am developing an app using react native, when I try to console.log(useDeviceOrientation());
我正在使用 react native 开发应用程序,当我尝试console.log(useDeviceOrientation());
. . The output ( true/false ) during the portrait and landscape did not change.纵向和横向期间的输出( true/false )没有改变。 Could someone help?有人可以帮忙吗?
The library that is used is: @react-native-community/hooks使用的库是:@react-native-community/hooks
API that I used: useDeviceOrientation我使用的 API:useDeviceOrientation
What I try to do:我尝试做的事情:
Code:代码:
// import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { Dimensions, StyleSheet, SafeAreaView, Alert, Button, Platform, StatusBar, View } from 'react-native';
import { useDimensions, useDeviceOrientation } from '@react-native-community/hooks'
export default function App() {
console.log(useDeviceOrientation());
const { landscape } = useDeviceOrientation();
return (
<SafeAreaView style={styles.container}>
<View style={{
backgroundColor: "dodgerblue",
width: "100%",
height: landscape ? "100%" : "30%",
}}
></View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
paddingTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
// justifyContent: "center",
// alignItems: "center",
},
});
There is no need of 3rd party library for this.为此不需要第 3 方库。 You can simply use this approach.您可以简单地使用这种方法。 First create a functional component named useOrientarion,首先创建一个名为 useOrientarion 的功能组件,
import { useWindowDimensions } from 'react-native';
const useOrientation = () => {
const height = useWindowDimensions().height;
const width = useWindowDimensions().width;
return { isPortrait: height > width };
};
export default useOrientation;
and then in your component,然后在你的组件中,
// import useOrientation
import useOrientation from './useOrientation';
function App() {
const orientation = useOrientation();
console.log(orientation);
// use orientation wherever you want
// OUTPUT: {"isPortrait": true} or {"isPortrait": false}
}
it works for me.这个对我有用。
const { height, width } = useDimensions().window;
const landscape = width > height;
I believe it is a known issue that they are working on: https://github.com/react-native-community/hooks/issues/210 .我相信这是他们正在处理的一个已知问题: https : //github.com/react-native-community/hooks/issues/210 。 @ReadRise answer works great as a workaround it though!不过,@ReadRise 答案作为一种解决方法非常有效!
I had the same issue;我遇到过同样的问题; stopping the app and re-building was sufficient to have it fixed.停止应用程序并重新构建足以修复它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.