react native - lock orientation of single screen with expo-screen-orientation - Stack Overflow

admin2025-04-29  2

I tried locking a single screen using useEffect and lockAsync with unlockAsync in the cleanup.

import {lockAsync, OrientationLock, unlockAsync} from 'expo-screen-orientation';
useEffect(() => {
    const lockOrientation = async () => {
      await lockAsync(OrientationLock.PORTRAIT);
    };

    lockOrientation();

    return () => {
      const unlockOrientation = async () => {
        await unlockAsync();
      };

      unlockOrientation();
    };
  }, [])

The cleanup function is not working - when I change screen I cannot change orientation any longer. If I add unlockAsync in the other screens then the orientation can change again.

Is there another way to lock the orientation of a single screen?

I tried locking a single screen using useEffect and lockAsync with unlockAsync in the cleanup.

import {lockAsync, OrientationLock, unlockAsync} from 'expo-screen-orientation';
useEffect(() => {
    const lockOrientation = async () => {
      await lockAsync(OrientationLock.PORTRAIT);
    };

    lockOrientation();

    return () => {
      const unlockOrientation = async () => {
        await unlockAsync();
      };

      unlockOrientation();
    };
  }, [])

The cleanup function is not working - when I change screen I cannot change orientation any longer. If I add unlockAsync in the other screens then the orientation can change again.

Is there another way to lock the orientation of a single screen?

Share Improve this question asked Jan 8 at 12:58 Federica TomolaFederica Tomola 1
Add a comment  | 

1 Answer 1

Reset to default 0

You can try useFocusEffect instead of useEffect.

import React, { useCallback } from 'react';
import { useFocusEffect } from '@react-navigation/native';
import { lockAsync, OrientationLock, unlockAsync } from 'expo-screen-orientation';

const YourScreen = () => {
  useFocusEffect(
    useCallback(() => {
      const lockOrientation = async () => {
        await lockAsync(OrientationLock.PORTRAIT_UP);
      };

      lockOrientation();

      return () => {
        const unlockOrientation = async () => {
          await unlockAsync();
        };

        unlockOrientation();
      };
    }, []) 
  );
};

export default YourScreen;

Hope this helps you :)

转载请注明原文地址:http://anycun.com/QandA/1745856678a91292.html