简体   繁体   中英

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

I have a function for detecting the window width and height on changing the layout.

The function for detecting width and height work fine but the problem is using them on stylesheet file.

The error is: Invalid hook call. Hooks can only be called inside the body of a function component.

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

Here is what I have tried in stylesheet (custom global stylesheet file):

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

You can use hooks only inside react components. Since useDimensions is a hook you can only use it like this:

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

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

Other than the fact hooks must be called inside a function use should remove the eventlistener inside the useEffect.

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

Use can get height and width simply by window.innerHeight and window.innerWidth . By this two you can get height and width of windows.

You can update your function like this:

import { Dimensions } from 'react-native';

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

And you can use it by importing:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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