Sin*_*kun 5 react-native react-native-android react-native-ios
我在 react-native 应用程序中使用纵向模式。但我想捕获屏幕的旋转事件。有没有办法做到这一点?
谢谢...
die*_*ris 10
useWindowDimensions()
要完成前面的答案,如果您只是希望您的应用程序具有响应能力,那么使用https://reactnative.dev/docs/usewindowdimensions会更容易,
只需在根组件中添加类似的内容即可:
const SCREEN_WIDTH = useWindowDimensions().width;
const SCREEN_HEIGHT = useWindowDimensions().height;
return (
<View style={{ width: SCREEN_WIDTH, minHeight: SCREEN_HEIGHT}} >
//the rest of your app
</View>
);
Run Code Online (Sandbox Code Playgroud)
此功能可能会帮助您
创建useOrientation.js文件
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;
}
Run Code Online (Sandbox Code Playgroud)
嗯,你有几个选择。您可以使用维度 API https://reactnative.dev/docs/dimensions
您可以为 Dimensions.change 添加监听器,您可以执行类似的操作
function isPortrait() {
const dim = Dimension.get("screen")
return dim.height >= dim.width
}
function isLandscape() {
const dim = Dimension.get("screen")
return dim.width >= dim.height
}
Run Code Online (Sandbox Code Playgroud)
现在添加监听维度变化
Dimensions.addEventListener("change", () => {
// orientation has changed, check if it is portrait or landscape here
})
Run Code Online (Sandbox Code Playgroud)
另一种可能性是使用可用的方向包之一,例如https://github.com/wonday/react-native-orientation-locker
| 归档时间: |
|
| 查看次数: |
10713 次 |
| 最近记录: |