【问题标题】:Why when I try to use react native hooks it does not work properly as intended to be?为什么当我尝试使用 react native 钩子时,它不能按预期正常工作?
【发布时间】:2020-11-07 03:21:58
【问题描述】:

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

使用的库是:@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",
  },
});

【问题讨论】:

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


【解决方案1】:

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

import { useWindowDimensions } from 'react-native';

const useOrientation = () => {
  const height = useWindowDimensions().height;
  const width = useWindowDimensions().width;

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

【讨论】:

    【解决方案2】:

    它对我有用。

    const { height, width } = useDimensions().window;
    const landscape = width > height;
    

    react-native-community

    【讨论】:

    • 我认为 OP 是说 useDeviceOrientation 钩子特别不起作用,因为我遇到了同样的问题,当方向改变时它的值不更新。这段代码非常有用,谢谢!
    【解决方案3】:

    我相信这是他们正在解决的一个已知问题:https://github.com/react-native-community/hooks/issues/210。 @ReadRise 答案作为一种解决方法非常有效!

    【讨论】:

      【解决方案4】:

      我有同样的问题;停止应用程序并重新构建足以修复它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-21
        • 2015-07-25
        • 1970-01-01
        • 1970-01-01
        • 2020-09-01
        相关资源
        最近更新 更多