gpt4 book ai didi

react-native - 如何在 StackNavigator 中模糊时卸载屏幕?

转载 作者:行者123 更新时间:2023-12-05 01:59:42 41 4
gpt4 key购买 nike

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

我怎样才能做到这一点?

最佳答案

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

  • 使用useFocusEffect 钩子(Hook)来触发一个 Action (推荐),或者
  • 使用useIsFocused 钩子(Hook),或者
  • 监听焦点事件
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} />;
}
useIsFocused Hook 示例
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};
}

注意:

Using this hook component may introduce unnecessary component re-renders as a screen comes in and out of focus. ...Hence we recommend to use this hook only if you need to trigger a re-render.

可以在文档中找到更多信息 Call a function when focused screen changes


除此之外,堆栈导航器带有一个名为 detachInactiveScreens 的 Prop ,默认情况下启用。 Link to the documentation

detachInactiveScreens

Boolean used to indicate whether inactive screens should be detached from the view hierarchy to save memory. Make sure to call enableScreens from react-native-screens to make it work. Defaults to true.

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

在堆栈导航器的 options 对象中,还有一个 detachPreviousScreen 属性来自定义某些屏幕的行为。通常也会启用此选项。

detachPreviousScreen

Boolean used to indicate whether to detach the previous screen from the view hierarchy to save memory. Set it to false if you need the previous screen to be seen through the active screen. Only applicable if detachInactiveScreens isn't set to false. Defaults to false for the last screen when mode='modal', otherwise true.

关于react-native - 如何在 StackNavigator 中模糊时卸载屏幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67674460/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com