问题
I am using portrait mode in react-native application. But I want to capture the rotation event of the screen. Is there a way to do this?
Thanks...
回答1:
Well, you have several options. You can use the Dimensions API https://reactnative.dev/docs/dimensions
You can add a listener for Dimensions.change and you could do something like
function isPortrait() {
const dim = Dimension.get("screen")
return dim.height >= dim.width
}
function isLandscape() {
const dim = Dimension.get("screen")
return dim.width >= dim.height
}
now add listen to dimension chagnes with
Dimensions.addEventListener("change", () => {
// orientation has changed, check if it is portrait or landscape here
})
Another posibility is to use the one of the orientation packages available such as https://github.com/wonday/react-native-orientation-locker
回答2:
this function might help you
create a useOrientation.js
file
import {useEffect, useState} from 'react';
import {Dimensions} from 'react-native';
export function useOrientation(){
const [orientation, setOrientation] = useState("PORTRAIT");
useEffect(() => {
Dimensions.addEventListener('change', ({window:{width,height}})=>{
if (width<height) {
setOrientation("PORTRAIT")
} else {
setOrientation("LANDSCAPE")
}
})
}, []);
return orientation;
}
来源:https://stackoverflow.com/questions/62472029/react-native-detect-screen-rotation-change-using-portrait-mode