繁体   English   中英

如何使用本机反应在样式表文件中获取 window 宽度和高度?

[英]How to get the window width and height in stylesheet file using react native?

我有一个 function 用于在更改布局时检测 window 宽度和高度。

用于检测宽度和高度的 function 工作正常,但问题是在样式表文件中使用它们。

错误是:无效的钩子调用。 钩子只能在 function 组件的内部调用。

我的Function:

import { useEffect, useCallback, useState } from 'react';
import { Dimensions } from 'react-native';

export function useDimensions () {

    const [windowWidth, setWindowWidth] = useState(Dimensions.get('window').width);
    const [windowHeight, setWindowHeight] = useState(Dimensions.get('window').height);

    useEffect(() => {
        
        const callback = () => {
            setWindowWidth(Dimensions.get('window').width);
            setWindowHeight(Dimensions.get('window').height);
        }
    
        Dimensions.addEventListener('change', callback);
    
    }, []);
  
    return {windowWidth, windowHeight};
};

这是我在样式表(自定义全局样式表文件)中尝试过的内容:

import { StyleSheet } from "react-native";
import Colors from "./Colors";
import { windowHeight, windowWidth } from '../App/Components/Dimensions';
import { useDimensions } from '../App/Components/TestDimesions';

// Here is the problem : Invalid hook call...
const orientation = useDimensions();

const Global = StyleSheet.create({
test:{
 width: windowWidht
}
});

export default Global

你只能在 React 组件中使用钩子。 由于useDimensions是一个钩子,你只能像这样使用它:

function MyComponent() {
  const orientation = useDimensions();

  return (
    <View style={[styles.test, { width: orientation.windowWidth }]} />
  )
}

除了必须在 function 内部调用挂钩之外,还应删除 useEffect 中的事件监听器。

useEffect(() => {
    //here 
    const listener = Dimensions.addEventListener('change', callback);
    return () => listener.remove();
}, []);

使用可以简单地通过window.innerHeightwindow.innerWidth获得高度和宽度。 通过这两个你可以得到windows的高度和宽度。

您可以像这样更新您的 function:

import { Dimensions } from 'react-native';

export const ScreenWidth = Dimensions.get('window').width;
export const ScreenHeight = Dimensions.get('window').height;

您可以通过导入来使用它:

import { StyleSheet } from "react-native";
import Colors from "./Colors";
import { ScreenWidth, ScreenHeight } from '../App/Components/TestDimesions';

const Global = StyleSheet.create({
  test:{
    width: ScreenWidth,
  }
});

export default Global

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM