下面的当前代码将获得方向,但是如果设备处于横向视图并且您打开应用程序,它会显示纵向视图。手动旋转设备后,下面的代码正常工作如何在应用程序启动时获取设备的方向。 #React #React Native
const ViewControllerProvider = (props) => {
const [orientation, setOrientation] = useState('PORTRAIT');
useEffect(() => {
Dimensions.addEventListener('change', ({window: {width, height}}) => {
if (width < height) {
setOrientation('PORTRAIT');
} else {
setOrientation('LANDSCAPE');
}
});
}, []);
return (
<ViewControllerContext.Provider value={{orientation}}>
{props.children}
</ViewControllerContext.Provider>
);
};
export {ViewControllerProvider, ViewControllerContext};
答案 0 :(得分:2)
添加监听器时,也可以手动调用获取初始方向:
const [orientation, setOrientation] = useState('LANDSCAPE');
const determineAndSetOrientation = () => {
let width = Dimensions.get('window').width;
let height = Dimensions.get('window').height;
if (width < height) {
setOrientation('PORTRAIT');
} else {
setOrientation('LANDSCAPE');
}
}
useEffect(() => {
determineAndSetOrientation();
Dimensions.addEventListener('change', determineAndSetOrientation);
return () => {
Dimensions.removeEventListener('change', determineAndSetOrientation)
}
}, []);
删除事件侦听器也可能是一个好主意(请参阅 return
语句)。