如何在 StackNavigator 中卸载模糊的屏幕?

abd*_*ech 7 react-native react-navigation-stack react-navigation-v5

我正在使用React Navigation x5,我正在StackNavigator加载一堆屏幕。unmountOnBlur我想在模糊时卸载一个特定的屏幕组件,以获得与使用DrawerNavigator.

我怎样才能做到这一点?

Tys*_*n Z 9

目前有三种方法可以做到这一点5.x。你可以

  • 使用useFocusEffect钩子触发操作(推荐),或者
  • 使用useIsFocused钩子,或者
  • focus事件
的例子useFocusEffect
import { useFocusEffect } from '@react-navigation/native';

function Sample(props) {
  const [shouldHide, setShouldHide] = React.useState(false);

  useFocusEffect(() => {
    setShouldHide(false)
    return () => {
       setShouldHide(true)
    }
  });

  return shouldHide ? null : <InnerComponent {...props} />;
}
Run Code Online (Sandbox Code Playgroud)
useIsFocused钩子示例
import * as React from 'react';
import { Text } from 'react-native';
import { useIsFocused } from '@react-navigation/native';

function Profile() {
  // This hook returns `true` if the screen is focused, `false` otherwise
  const isFocused = useIsFocused();

  return {isFocused ? <Text>Inner component</Text> : null};
}
Run Code Online (Sandbox Code Playgroud)

笔记:

当屏幕进入和离开焦点时,使用此钩子组件可能会导致不必要的组件重新渲染。...因此,我们建议仅在需要触发重新渲染时才使用此挂钩。

更多信息可以在文档中找到,当焦点屏幕改变时调用函数


除此之外,堆栈导航器还带有一个名为的 prop detachInactiveScreens,默认情况下启用。文档链接

detachInactiveScreens

布尔值用于指示是否应从视图层次结构中分离非活动屏幕以节省内存。请务必致电enableScreensreact-native-screens使其正常工作。默认为true.

(有关启用 React Native Screens 的说明可以在https://reactnavigation.org/docs/react-native-screens/#setup-when-you-are-using-expo找到)

在堆栈导航器的options对象内部,还有一个detachPreviousScreen用于自定义某些屏幕行为的道具。通常也会启用此选项。

detachPreviousScreen

布尔值用于指示是否从视图层次结构中分离上一个屏幕以节省内存。false如果您需要通过活动屏幕看到上一个屏幕,请将其设置为。detachInactiveScreens仅当未设置为 false时才适用。当 时,默认false为最后一个屏幕mode='modal',否则true