首页 > 解决方案 > React Native - 在样式表中使用 useDimensions 钩子

问题描述

您如何在样式表中使用从 RN 中的钩子返回的尺寸?

例如

import { useDimensions } from '@react-native-community/hooks';

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

const styles = StyleSheet.create({
  profileEditContainer__form: {
    borderRadius: 15,
    height: 40,
    width: width - width / 4,
    borderColor: Colors.defaultColor,
    borderWidth: 1,
    textAlign: 'center',
  },
  ...

在上面的例子中,widthnot defined

过去(类组件),我曾经有一个顶级的

const { width: WIDTH } = Dimensions.get('window');

用功能组件真的不能再这样做了..有什么建议吗?

标签: react-nativereact-hooks

解决方案


  1. 您只能在功能组件中使用钩子。
  2. 对于您的示例,我仍然建议使用Dimensions.get('window').

推荐阅读