如何用React Navigation 5复制onDidBlur或onWillBlur?

问题描述 投票:0回答:1

正如他们所指出的 在文档中他们已经摆脱了4个导航事件监听器,而决定使用 生命周期事件.

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

我怎样才能复制 onWillBluronDidBlur 这样的用例的事件?我不需要知道在用户点击按钮后被带到B屏幕后,A屏幕是否模糊。

react-native react-navigation
1个回答
0
投票

你可以使用钩子useFocusEffect。

文档在这里

EDIT:

添加了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 />;
}

EDIT 2.我没有在主页按钮上测试它,但我找到了一个帖子,对这个问题也有帮助。

我没有在主页按钮上进行测试,但我找到了一个帖子,也能帮到你。

查看这里

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

在这里,你有一个工作的例子。

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>
}
© www.soinside.com 2019 - 2024. All rights reserved.