【问题标题】:How to replicate onDidBlur or onWillBlur with React Navigation 5?如何使用 React Navigation 5 复制 onDidBlur 或 onWillBlur?
【发布时间】:2020-04-22 16:34:04
【问题描述】:

正如他们指出的 in the docs,他们已经摆脱了 4 个导航事件侦听器,而是决定使用 Lifecycle events。

但是我在使用 React Navigation 5 时遇到的问题是 blur 事件无法正常工作!以前,我可以添加一个onWillBlur 侦听器,并在用户暂时离开(而不是关闭)应用程序时做一些事情(例如关闭套接字连接,然后在用户重新进入应用程序时重新打开它)。

如何为此类用例复制 onWillBlur 或 onDidBlur 事件?用户点击按钮后进入屏幕 B 后,我不需要知道屏幕 A 是否模糊。

【问题讨论】:

    标签: react-native react-navigation


    【解决方案1】:

    你可以使用钩子useFocusEffect。

    Documentation here

    编辑:

    添加了来自 React Navigation 的示例。

    import { useFocusEffect } from '@react-navigation/native';
    
    function Profile() {
      useFocusEffect(
        React.useCallback(() => {
          // Do something when the screen is focused, onFocus
    
    
          return () => {
            // Do something when the screen is unfocused, onBlur
            // Useful for cleanup functions
          };
        }, [])
      );
    
      return <ProfileContent />;
    }
    

    编辑 2:

    我没有在主页按钮上对其进行测试,但我发现了一篇文章也对此有所帮助

    Check here

    希望这次你对我的回答感到满意。

    这里有一个工作示例:

    import React from 'react'
    import { Text, AppState } from 'react-native'
    
    const MyComponent = () => {
    
        const [appState, setAppState] = React.useState(AppState.currentState)
    
        React.useEffect(() => {
          AppState.addEventListener('change', handleChanges)
    
          setAppState(AppState.currentState)
    
          return AppState.removeEventListener('change')
        },[])
    
        const handleChanges = (nextAppState) => {
            if (appState.match(/inactive|background/) && nextAppState === 'active') {
    
              console.log('App has come to the foreground!');
            } else {
              console.log('App has gone to the background!');
              // start your background task here
            }
    
            setAppState(nextAppState)
        }
    
        return  <Text>{appState}</Text>
    }
    

    【讨论】:

    • 这不会让您知道用户单击其主页按钮并离开应用程序后屏幕是否模糊。
    猜你喜欢
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 2020-10-14
    • 2020-08-08
    • 2021-01-09
    • 1970-01-01
    相关资源
    最近更新 更多