javascript - 为什么当我尝试使用 React Native Hooks 时,它不能按预期正常工作?

标签 javascript react-native react-hooks device-orientation

当我尝试 console.log(useDeviceOrientation()); 时,我正在使用 React Native 开发一个应用程序。纵向和横向期间的输出(真/假)没有改变。有人可以帮忙吗?

使用的库是:@react-native-community/hooks

我使用的API:useDeviceOrientation

我尝试做的事情:

  1. 卸载库
  2. 重新安装相同的库
  3. 将库的依赖项添加到package.json
  4. 发生了同样的问题。改变方向时没有变化

代码:

// 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",
  },
});

最佳答案

为此不需要第三方库。您可以使用这种方法。 首先,创建一个名为useOrientarion的功能组件,

import { useWindowDimensions } from 'react-native';

const useOrientation = () => {
  const { width, height } = useWindowDimensions();

  return { isPortrait: height > width };
};

export default useOrientation;

然后在你的组件中,

// 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}
}

关于javascript - 为什么当我尝试使用 React Native Hooks 时,它不能按预期正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64724129/

相关文章:

react-native - Expo 不适用于 firebase 模拟器

javascript - 在平面列表中使用本地 img (React-Native)

javascript - 在我的例子中,如何只使用一次 react hook useEffect?

javascript - 如何解决这个错误 "Uncaught TypeError: inputArgs[0].match is not a function"

javascript - 模拟外部依赖

javascript - 如何制作固定高度的无限水平容器

react-native - 使用 editable=true 和 dataDetectorTypes 响应 Native TextInput

javascript - 如何同时从多个url获取数据?

javascript - 如何基于 javascript/typescript 中的另一个数组创建动态数组?

JavaScript mouseup 和 mousedown 事件