You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native使用useDimensions()报错:undefined is not a function 求解决

解决@react-native-community/hooks中useDimensions报错问题

你遇到的undefined is not a function错误,核心原因是**@react-native-community/hooks的新版本已经移除了useDimensions钩子**,而useDeviceOrientation目前仍在库中保留,所以能正常使用。

解决方案1:改用React Native内置的useWindowDimensions

React Native从0.63版本开始,已经内置了useWindowDimensions钩子,功能和原useDimensions完全一致,且官方维护更稳定。修改代码如下:

import {
  StyleSheet,
  SafeAreaView,
  Platform,
  StatusBar,
  View,
  useWindowDimensions // 从react-native导入内置钩子
} from 'react-native';

import {
  useDeviceOrientation // 保留库中的这个钩子
} from '@react-native-community/hooks';

export default function App() {
  console.log(useWindowDimensions()); // 替换为内置钩子
  
  return (
    <SafeAreaView style={styles.container}>
      <View style={{
        backgroundColor: 'dodgerblue',
        width: "100%",
        height: "30%"
      }}></View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    paddingTop: Platform.OS === 'android' ? StatusBar.currentHeight : 0,
  },
});

解决方案2:回退到旧版本的社区库(不推荐)

如果你坚持要使用社区库的useDimensions,可以安装该库还包含这个钩子的旧版本,比如v2.8.1:

npm install @react-native-community/hooks@2.8.1
# 或者用yarn
yarn add @react-native-community/hooks@2.8.1

不过更建议使用官方内置的useWindowDimensions,避免后续库更新带来的兼容性问题。

内容的提问来源于stack exchange,提问作者iamnomadgg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 18:22:55