我在反应本机应用程序中使用纵向模式。但我想捕获屏幕的旋转事件。 有办法做到这一点吗?
谢谢...
这个功能可能对你有帮助
创建一个
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;
}
为了完成之前的答案, 如果您只是希望您的应用程序具有响应能力,那么使用起来更容易
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>
);
与 useWindowDimensions
import {useWindowDimensions} from "react-native"
export function useIsLandscape() {
const {height, width} = useWindowDimensions()
return width > height
}
2022 年快速、简单的本机钩子实现。
嗯,你有几种选择。您可以使用维度 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
}
现在添加聆听维度变化
Dimensions.addEventListener("change", () => {
// orientation has changed, check if it is portrait or landscape here
})
另一种可能性是使用可用的方向包之一,例如 https://github.com/wonday/react-native-orientation-locker
useDeviceOrientation:将返回一个对象,每次设备更改方向“真或假”时都会更新该对象
import { useDeviceOrientation } from "@react-native-community/hooks";
useDeviceOrientation
返回的示例对象:
{
"landscape": false,
"portrait": true,
}
我们可以解构对象:
const { landscape } = useDeviceOrientation();
比我们可以使用它:
height: landscape ? "100%" : "30%"
使用 React Native 0.73 我只需在 useEffect()
中添加一个
listener:
useEffect(() => {
const subscription = Dimensions.addEventListener('change', ({window, screen}) => {
// code that runs when the orientation changes
},
);
return () => subscription?.remove();
});